Search code examples
javaoopinheritanceencapsulation

Acessing grandparent's method in java


i am working on practice problems simple OOP concepts using java the question gives a uml diagram and asks to implement . i went through a problem it asks me to access a method in the grandparent class from the child class.

see illustration :

    
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(); // Trying to access Grandparent's Print() 
        System.out.println("Child's Print()"); 
    } 
} 

public class Main { 
    public static void main(String[] args) { 
        Child c = new Child(); 
        c.Print(); 
    } 
} 
 

i have done my reasearch everywhere i found that java doesn't allow that due to apllying Encpculation however it is allowed in C++ , my question is can i do something to get that method from grandparent class beside the not allowed ( super.super.method() ) statement in java .

i mean can i change the structure in such a way i kep the inhertiance as it is and can access that method with missing the UML .


Solution

    1. There is no way to call super.super.foo() in java.

    2. You can do it implicitly by:

      public class Grandparent {
          public void Print() { 
              System.out.println("Grandparent's Print()"); 
          } 
      }
      class Parent extends Grandparent { 
          public void Print() { 
              super.Print(); // Here we can add a call to Print() from Grandparent.
              System.out.println("Parent's Print()"); 
          } 
      } 
      
      class Child extends Parent { 
          public void Print() { 
              super.Print(); 
              System.out.println("Child's Print()"); 
          } 
      } 
      
      public class Main { 
          public static void main(String[] args) { 
              Child c = new Child(); 
              c.Print(); 
          } 
      } 
      
    • Note: Try to use naming conventions for methods. Use lowerCamelCase for Print() -> print()