// 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?