Using super, how to access grandparent’s member in java

Directly accessing Grandparent’s member in Java:

Guess the output of the following Java program.

In Java, accessing a grandparent's member can be accomplished using the "super" keyword. However, since Java does not support multiple inheritance, it can be a bit more complicated than simply using the "super" keyword to access a parent's member.

To access a grandparent's member in Java, you can use the "super" keyword twice. First, you use "super" to access the parent's member, and then you use "super" again to access the grandparent's member. This is done using the dot operator.

Let's say we have a class hierarchy that looks like this: 

 

public class Grandparent {
   public int grandparentField;
}

public class Parent extends Grandparent {
   public int parentField;
}

public class Child extends Parent {
   public int childField;
}

To access the "grandparentField" member of the "Grandparent" class from the "Child" class, you would use the following code: 

 

public class Child extends Parent {
   public int childField;
   
   public void accessGrandparentField() {
      int grandparentField = super.super.grandparentField;
   }
}

Note that this code may result in a compiler error, as it is not recommended to access a grandparent's member directly in Java. Instead, it is better to create a method in the parent or grandparent class that returns the desired member value, and call that method from the child class.

Submit Your Programming Assignment Details