-1

As one can see in 4th line, an object of type grandad has been assigned to the reference of type father. In the 5th line, string "Prasad" has been passed as the parameter to the function setname() and the control jumps to setname() function in class father. This is evident because a print statement has been placed inside the function prints Prasad. In 6th line name variable of the same object has been tried to access which makes the control fetch the content of name variable from grandad class ("Sample") which is ironic as the object is the same. The output is: Prasad Sample

public class Main
{
    public static void main(String[] args) {
        grandad g = new father();
        g.setname("Prasad");
        System.out.println(g.name);
    }
}
class grandad
{
    String name="Sample";
    public void setname(String name)
    {
        this.name = name;
    }
}
class father extends grandad
{
    String name;
    public void setname(String name)
    {
        this.name = name;
        System.out.println(this.name);
    }
}

1 Answers1

0

When considering polymorphism in java the things that are overridden are the methods and not the variables. So when you have two variables of the same name, one in the subclass and one in the super, the variable in the super class hides the variable in the subclass (as long as they have the same name.

This link below goes further into this concept known as variable hiding.

https://dzone.com/articles/why-instance-variable-of-super-class-is-not-overri