override - confusing on java overriding vs polymorphism -


i don't know if question related overriding or polymorphism hence looking forward advise.

refer following coding,

    father f=new father();     f.eat();             // display father's eat()     son s=new son();     s.eat();             // display son's eat()     father x=new son();     x.eat();             // display son's eat() 

it learned

son s=new son();         s.eat(); 

and

father x=new son();         x.eat(); 

would display same result, wonder why tutorial mentioned using

father x=new son();             x.eat(); 

instead of using

son s=new son();             s.eat(); 

directly?

in practice common, don't use class it's real type (like son in case), rather 1 of it's super-classes (like father in case) or 1 of it's interfaces (like serializable class if have).

it useful in polymorph languages java don't need know real class, can use more generic one. example, if draw shapes, hold them in 'list<drawable>' drawables' list, where

interface drawable {    //drawes shape on screen    public void drawme(); } 

and there implementation classes of rectange or triangle.

now, in 'business logic' don't want know details of rectangles or triangles or further shapes, thing need know, class implements drawable interface, can call 'drawme' method on it, can go through list items this

for(drawable d: drawables) {   d.drawme(); } 

i hope give insight on :)


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -