2

This code prints "GenericAnimal", where as I was expecting it to print "PolymorphismTest" as I created an object of PolymorphismTest.

class GenericAnimal{
    String name="GenericAnimal";
}

public class PolymorphismTest extends GenericAnimal {
    String name = "PolymorphismTest";

    public static void main(String[] args) {
        GenericAnimal animal = new PolymorphismTest();
        System.out.println(animal.name);
    }
}
Danielson
  • 2,605
  • 2
  • 28
  • 51
Sandeep D
  • 157
  • 7
  • 3
    possible duplicate of [overriding variables java](http://stackoverflow.com/questions/10722110/overriding-variables-java) – jaco0646 Aug 08 '15 at 14:09

3 Answers3

0

It's called field "hiding" or "shadowing". You have a second field of the same name as the field in the parent class. If the one in the parent were private then it would not be accessible to the subclass.

The extra String name field in the subclass occupies its own memory and reference. You probably should re-use the field of the parent class by either making it visible (i.e. protected or public scope) or adding a protected or public accessor and mutator to the parent class that the subclass can invoke to access and manipulate the field.

Paul Bilnoski
  • 556
  • 4
  • 13
0

Because you're accessing the field, rather that a function. The second field shadows the one in the superclass, rather than overriding. This is not the same as the behaviour of functions, which is probably what you were looking for here:

class GenericAnimal {
    String name = "GenericAnimal";

    public String getAnimal(){
        return name;
    }
}

public class PolymorphismTest extends GenericAnimal {

    String name = "PolymorphismTest";

    public static void main(String[] args) {

        GenericAnimal animal = new PolymorphismTest();
        System.out.println(animal.name);
        System.out.println(animal.getAnimal());

        PolymorphismTest testAnimal = (PolymorphismTest)animal;
        System.out.println(testAnimal.name);
        System.out.println(testAnimal.getAnimal());

    }

    public String getAnimal(){
        return name;
    }
}
hugh
  • 2,237
  • 1
  • 12
  • 25
0

Your GenericAnimal reference cannot reference to the property of its subclass PolymorphismTest. Property values cannot be overridden in java, only the methods.

Note: This is NOT about hiding at all. (That would be the other direction of reference.)

Laszlo Hirdi
  • 1,140
  • 12
  • 18