Java | Inheritance | Question 8
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(); } } |
chevron_right
filter_none
(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();
}
}
Recommended Posts:
- Java | Inheritance | Question 3
- Java | Inheritance | Question 7
- Java | Inheritance | Question 9
- Java | Inheritance | Question 5
- Java | Inheritance | Question 4
- Java | Inheritance | Question 1
- Java | Inheritance | Question 2
- Java | Inheritance | Question 9
- Inheritance in Java
- Using final with Inheritance in Java
- Delegation vs Inheritance in Java
- Inheritance and constructors in Java
- Java and Multiple Inheritance
- Interfaces and Inheritance in Java
- Comparison of Inheritance in C++ and Java



