Java | Inheritance | Question 8

Predict the output of following Java Program

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


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


Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.