This output make me confused.
Present Code First:
public class Animal{
int age;
public Animal(int age){
this.age = 0;
}
public int getAge(){
return age;
}
}
public class Wolf extends Animal{
int age;
Wolf(int age){
super(age);
this.age = age;
}
}
public class MainTest {
public static void main(String[] args){
Wolf wolfExample = new Wolf(2) ;
System.out.println("Age = " + wolfExample.getAge());
}
}
The output is:
0
My expected output is:
2
through debug this program it seemed that wolfExample.getAge()
return the age of its parent not itself, why? base on polymorphism here should return the age of wolf,
I will appreciate if you can give me some guide.
Note: Currently, I find inheritance is far difficult than what I think before.
getAge method
too. Why jvm dont invoke the child's method. I think if *use override, child has a method of its own otherwise the method is belong to parent the child only has a authority to use it*. I dont know whether my thought is true? – liushui Nov 28 '16 at 08:03