0
// Parent class
class Parent {
    String name = "Parent Name";
 
    void method()
    {
        System.out.println("Method from Parent");
    }
}
 
// Child class
class Child extends Parent {
    String name = "Child Name";
 
    // Overriding the parent method
    @Override void method()
    {
        System.out.println("Method from Child");
    }
}
 

public class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
        // Upcasting
        Parent p = new Child();
 
      
        System.out.println(p.name); // prints parent's version ???
        
        p.method(); // prints child's version

    }
}

When upcasting Child to Parent, the child's method is called... However, the child's attribute (ie name) is not called, the parent's name is called. So, it appears that only the child's version of the functionality is called, but the parent's attribute versions are called. Why is this? Since we are hiding the parent's name in the child, shouldn't the child's name be called too?

Grateful
  • 9,685
  • 10
  • 45
  • 77
  • 1
    Because methods are polymorphic but attributes aren't. – user207421 Aug 22 '22 at 04:40
  • 2
    Fields cannot be overridden, only hidden. Which field you're referencing is resolved statically. So, since the variable type is `Parent`, you're referencing `Parent.name` instead of `Child.name`. You'd see the same thing with static methods. – Slaw Aug 22 '22 at 04:40

0 Answers0