How to override an indirectly called method

I'm not really sure how to properly capitalize this question, I'll just try to describe it as clear as possible:

Interface InterfaceB {
  void methodB();
}

Class ClassB implements InterfaceB {
  void methodB() {
    //...
  }
}

Class ClassA {
  InterfaceB methodA() {
    return new ClassB();
  }
}

      


Class MyClass {
  public static void main(String[] args) {
    ClassA a = new ClassA();
    InterfaceB b = a.methodA();
    b.methodB();  // override this guy
  }
}

      

I want to override methodB without changing ClassA and ClassB. Appreciate any ideas.

+3


source to share


3 answers


This is what you can do:

ClassA a = new ClassA() {//extend class A

 InterfaceB methodA() {//Override methodA
    return new ClassB() {//extend class B
       void methodB() {//Override methodB
       //...
       }
    };
  }
};

      



You have a method overB without changing either class A or class B. That being said, you don't really need to extend with ClassA. You can create factory

, pass it to class A as a dependency and pass a parameter methodA

specifying which specific implementation classB

to use to callmethodB

+2


source


Because methodA

of ClassA

always returns an instance ClassB

, if you want to override ClassB

methodB

, you need to expand the ClassA and ClassB and override methodA

and methodB

subclasses.

class ClassSubB extends ClassB {
  @Override
  void methodB() {
    //...
  }
}

class ClassSubA extends ClassA {
  @Override
  InterfaceB methodA() {
    return new ClassSubB();
  }
}

      



Now

class MyClass {
  public static void main(String[] args) {
    ClassA a = new ClassSubA(); // create an instance of ClassSubA
    InterfaceB b = a.methodA(); // will return an instance of ClassSubB
    b.methodB();  // will call methodB of ClassSubB
  }
}

      

+1


source


Interface InterfaceB {
  void methodB();
}

Class ClassB implements InterfaceB {
  void methodB() {
    //...
  }
}

class ClassSubClassB extends ClassB {
@Override
void methodB() {
    //...
  }
}

Class ClassA {

  InterfaceB methodA(boolean overriddenMethod) {
if(overriddenMethod)
    return new ClassSubClassB();
else
    return new ClassB();
  }
}
Class MyClass {
  public static void main(String[] args) {
    ClassA a = new ClassA();
    InterfaceB b = a.methodA(true);
    b.methodB();  // override this guy
  }
}

      

This will work without overriding class A. Ideally you should create a factory class where you delegate the job of creating the object. This way, you will create the required instances based on certain conditions.

-1


source







All Articles