1

Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in class A invoke the test()method defined in class C?

Answer is "It is not possible to invoke test()".

class C {
  
    public static void test(){
        System.out.println("IMESH ISURANGA");
    }
}
  
class B extends C {
  
}

class A extends B {
  //how prove it
}
  
class Demo {
  
    public static void main(String[] args) {
  
        //----
        
    }
}

How to prove it?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
  • Does this answer your question? [Java Inheritance - calling superclass method](https://stackoverflow.com/questions/6896504/java-inheritance-calling-superclass-method) – İsmail Y. Aug 31 '21 at 07:13
  • 1
    Hint: the exercise you are trying to solve is about non-static methods ... not static methods. – Stephen C Aug 31 '21 at 07:14
  • The key is in "all the three classes implement the method test()" You are missing the methods in class B and C. If you implement these, the function 'test()' in class B will override the one of class C. As A extends B, A can only use 'super.test()' which will call the implementation of class B. as Stephen has indicated: your method should not be static. – Stijn Dejongh Aug 31 '21 at 07:29

1 Answers1

0

The answer is "It is not possible to invoke test()". Because if it's possible, it would break encapsulation.

We can invoke the test() method in class B using "super." keyword. This happens under the assumption that we are aware that we are violating the encapsulation on our own class. But we are not allowed to access the class above the parent class using "super." keywords because we don't know what rules the superclass is enforcing. So, we can't bypass an implementation.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Klord
  • 5
  • 4