Tuesday, 11 July 2017

Java: How do you access a parent class method two levels down?

We don't: it violates encapsulation.

It is fine to say, "No, I don't want my own behavior - I want my parent's behavior" because it's assumed that you'll only do so when it maintains your own state correctly.

However, you can't bypass your parent's behavior - that would stop it from enforcing its own consistency. If the parent class wants to allow you to call the grandparent method directly, it can expose that via a separate method... but that's up to the parent class.

Workaround using flag:
package com.java.oops;
/**
 * Grand Parent Class
 */
class AClass {
     public void method(boolean gpFlag) {
           System.out.println("Class A");
     }
}

/**
 * Parent Class.
 */
class BClass extends AClass {
     public void method(boolean gpFlag) {
           super.method(gpFlag);
           if(gpFlag) {
                return;
           }
           System.out.println("Class B");
     }
}

/**
 * Child Class.
 */
class CClass extends BClass {
     public void method(boolean gpFlag) {
           super.method(gpFlag);
           System.out.println("Class C");
     }
}

public class CallGrandParent {
     public static void main(String[] args) {
           CClass c = new CClass();
           boolean gpFlag = true;
           c.method(gpFlag);
     }
}
Output:
Class A
Class C



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...