liushui liushui - 12 days ago 5
Java Question

Why the polymorphism dont play a role?

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.

Answer

Polymorphism exists for methods, not for fields. Therefore getAge(), which is only implemented in the Animal class, returns the member of the Animal class.

If you override getAge() in the Wolf class, i.e. add a

@Override
public int getAge() {
    return age;
}

you'll get the value of the Wolf class member.

That said, it doesn't make sense to have an age member in both the base class and sub-class. If it's a property common to all Animals, it should only be in the Animal class.

So your Wolf class will become :

public class Wolf extends Animal {
    Wolf(int age) {  
        super(age);
    }
}

And your Animal constructor doesn't make sense. You should assign the passed age argument to the member of the class :

public Animal(int age) {
    this.age = age;
}