0

I have several classes:

public class SubclassA extends ClassA implements InterfaceA

public class SubclassB extends ClassB implements InterfaceA

public class SubclassC extends ClassC implements InterfaceA

...

is there any possibility to redirect all functioncalls to functions you can find in the interface to another class/object?

means if that is the interface:

public interface InterfaceA{

    public void doIt();

}

and that is the HelperClass:

public class HelperClass implements InterfaceA{

    public void doIt(){
        ...
    }

}

is it possible that i redirect all calls of the the classes SubclassA, SubclassB, SubclassC etc to the function doIt() of the HelperClass? (Ofc without writing the calls into every implementation of every function) or if there is no way do you know a way to let it eclipse do? there are lots of classes where i would need to write the same...

I'd be happy if anybody could show me a way to do that. Thanks in advance.

rapus95
  • 31
  • 4

3 Answers3

1

You can use either an abstract class for that or you wait for Java 8. There we get default implementations for interfaces. See: http://blog.hartveld.com/2013/03/jdk-8-13-interface-default-method.html

In more complex applications you can use Aspect Oriented Programming (aop) for that. But I guess this is not an option for you.

d0x
  • 11,040
  • 17
  • 69
  • 104
0

Create an abstract class that implements the InterfaceA interface, basically make your HelperClass abstract

public abstract class HelperClass implements InterfaceA {
    public void doIt(){
        ... // do it
        reallyDoIt();
    }

    public abstract void reallyDoIt();
}

Then make your classes extend HelperClass instead.

To answer

is it possible that i redirect all calls

No, it is not possible. You can only do that for the methods on the interface that you explicitly implement in the abstract parent class.

Another solution would be to use Aspect Oriented Programming to intercept all method calls from any class. That subject is a little more advanced so I recommend you look it up if you're interested. The more I think about it the more I think AOP is the way to go for you.

Take a look at this answer.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • This will not work in his class hierarchy. Then he need to adjust ClassA, B, C aswell, correct? – d0x Sep 08 '13 at 17:19
  • @ChristianSchneider You are correct, OP will have to propagate this behavior to each of those classes. Possibly making ClassA, ClassB, etc extend `HelperClass` – Sotirios Delimanolis Sep 08 '13 at 17:20
0

In Java8 there will be a feature called default methods. This basically means interfaces can provide a default implementation of a method that it declares.

You can find an explanation of this feature here:

http://www.angelikalanger.com/Lambdas/LambdaTutorial/lambdatutorial_5.html

phlogratos
  • 13,234
  • 1
  • 32
  • 37