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);
}
}