IKo
IKo

Reputation: 5816

Why the value of parent variable is used instead of value of child variable when the type of the object is child?

public class Parent {

    String name = "parent";

    public static class Child extends Parent {
        String name = "child";
    }

    public static void main(String[] args) {
        Parent p = new Child();
        Child c = new Child();
        System.out.println(p.name);   //parent
        System.out.println(c.name);   //child
    }
}

There is a rule that the type of the object defines which properties exist in memory. So my question is why the output of the p.name is 'parent' but not 'child' when the type of the p object is Child?

Upvotes: 2

Views: 60

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 122026

why the output of the p.name is 'parent' but not 'child' when the type of the p object is Child?

Because ovverriding/polymorphism applies only on methods. Variables still bind to its type. In your case type is Parent, hence you seeing the variable from Parent.

Upvotes: -1

davidxxx
davidxxx

Reputation: 131546

Because defining a field with the same name in the subclass doesn't override the field in the parent class.

Methods are overridable, fields are not.

Here p.name refers the name of the Parent declared type :

    Parent p = new Child();
    Child c = new Child();
    System.out.println(p.name);   //parent

Upvotes: 2

Related Questions