Inheritance concept in Java -


this rather basic question. can't understand concept of inheritance.

suppose have 2 classes, , b both have test() method returned 1 , 2 respectively, , b inherited class. in main method declare instance such;

a a1 = new b();

and call method a1.test(), return 2. concept of polymorphism. when have method test2() in subclass, can't call method using same instance declaration above. why happen?

i can't call method using same instance declaration above. why happen?

because type of variable a, , class a not have method test2(). java compiler looks @ type of variable check if can call method, not @ actual object (which in case b).

this easier understand if use more concrete , meaningful names classes, instead of abstract names such a , b. let's call them animal , bear instead:

class animal { }  class bear extends animal {     public void growl() { ... } }  class cat extends animal {     public void meow() { ... } }  animal a1 = new bear(); animal a2 = new cat();  // doesn't work, because not every animal bear, , not // animals can growl. a1.growl();  // wouldn't expect work, because a2 cat. a2.growl(); 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -