Predict the output of following Java Program
// filename Main.java class Grandparent {
public void Print() {
System.out.println( "Grandparent's Print()" );
}
} class Parent extends Grandparent {
public void Print() {
System.out.println( "Parent's Print()" );
}
} class Child extends Parent {
public void Print() {
super . super .Print();
System.out.println( "Child's Print()" );
}
} public class Main {
public static void main(String[] args) {
Child c = new Child();
c.Print();
}
} |
(A) Compiler Error in super.super.Print()
(B)
Grandparent's Print() Parent's Print() Child's Print()
(C) Runtime Error
Answer: (A)
Explanation: In Java, it is not allowed to do super.super. We can only access Grandparent’s members using Parent. For example, the following program works fine.
// Guess the output // filename Main.java class Grandparent { public void Print() { System.out.println("Grandparent's Print()"); } } class Parent extends Grandparent { public void Print() { super.Print(); System.out.println("Parent's Print()"); } } class Child extends Parent { public void Print() { super.Print(); System.out.println("Child's Print()"); } } class Main { public static void main(String[] args) { Child c = new Child(); c.Print(); } }