0

Good day developers.

So there is the problem:

I need my class MyClass implements the interface IMyInterface with method doSomething(); and overrides method doSomethiing() the other class let's call him TheOtherClass also implements IMyInterfaceand overrides method doSomethiing() and plus realize some logic of this doSomething() method(In TheOtherClass).

Question:

  • How can I make doSomething() method implemented in MyClass trigger doSomething() from TheOtherClass automaticaly
  • Also if MyClass invoked I want doSomethig() method invoke automaticaly??

2 Answers2

1

I think something like this.

public class TheOtherClass implements IMyInterface{
  public void doSomething(){}
}

public class MyClass implements IMyInterface{

// Instance initialization block:
// Runs before the constructor each time you instantiate an object
 {
   this.doSomething()
 }

  public MyClass(){
  }

  IMyInterface theOtherClass = new TheOtherClass ();

  public void doSomething(){
    theOtherClass .doSomething();
    //Add more logic here
  }
}

Instead of call doSomething in constructor as per this thread link I suggest use the instance initialization blocks read more here

Community
  • 1
  • 1
Koitoer
  • 18,778
  • 7
  • 63
  • 86
  • This is hardcoding anyway. I would prefer to add public class MyClass implements IMyInterface to MyClass and only override doSomethig() this is it. Is it possible? I know I use Spring and ypu implement Interface with method and they will trigger automaticaly. Also my wishes – user3013553 Feb 07 '14 at 07:26
  • You never said something about spring XD, that change the context – Koitoer Feb 07 '14 at 07:27
  • I suggest then to use AOP to invoke operations on the case of certain methods or constructors are invoked. Please update your question with that or open a new one an select the correct one for this. – Koitoer Feb 07 '14 at 07:28
0

You can try this

1. make MyClass sub-class of TheOtherClass
2. call to super.doSumething() in MyClass's doSomething() method.

this will serve both of your purposes. And b'coz it will be overriding you can change the logic in the method. for details click here

Saurabh Sharma
  • 489
  • 5
  • 20