I have a interface with one method:
public interface MyInterface {
public void doSomething();
}
And multiple concrete implementations of 'MyInterface':
Implementation1:
public class Implementation1 implements MyInterface {
@Override
public void doSomething() {
// DO something for implementation1
}
}
Implementation2:
public class Implementation2 implements MyInterface {
@Override
public void doSomething() {
// DO something for implementation2
}
}
and implementation3:
public class Implementation3 implements MyInterface {
@Override
public void doSomething() {
// DO something for implementation3
}
public void doSomething(int something) {
// DO something for implementation3
}
}
if I want to access 'doSomething(10)' with 'MyInterface' type I need to add this function to 'MyInterface' and other implementation ('Implementation1' and 'Implementation2' in my example) must to implement this function but do nothing because I don't need this function in 'Implementation1' and 'Implementation2'.
My question is: How to proceed in this case? implement 'doSomething(int something)' and let them to do nothing in 'Implementation1' and 'Implementation2' only for 'Implementation3' or to cast instance variable to 'Implementation3' and in this way create a dependency to concrete type 'Implementation3'? I want to specify that I don't want to create dependencies on concrete implementations because I want to let the interfaces communicate with each other.
Thanks!
One solution is to have 2 interfaces, the first one, which you already have:
and the second which extends from the first and so it already has the parameter-less method as well as the second method overload which takes an int parameter:
Then if a concrete class needs both methods, it can implement the second interface:
Note that instances of the above class can still be used in places where MyInterface type is expected.