Having only a small amount of time to search for such things, I could not see anything that covered my specific scenario.
I am working with a 3rd party interface. Let us say for a moment it is as follows:
public interface interface1
{
public String getVar1();
public void method1();
public void method2();
}
I need to create a number of classes that make use of this interface but the actual method implementation of "method2" would differ on each,where as "method1" and "getVar1" would always be the same code.
Is there any way to create an abstract base class that implements the interface but only forces the implementation of "method2" onto the child classes?
I had tried
public abstract @Override void method2
but while this is "acceptable" at design time in Netbeans (don't know if Eclipse acts differently) at compile time it complains that method2 needs to be implemented.
If it is not possible, fair enough, I just need to check.
thanks
You can do this by creating an abstract class that implements the interface. Any sub-class of this abstract class will be required to implement any interface methods that were not yet defined.
public abstract class AbstractInterface implements interface1 {
@Override
public String getVar1() {
}
@Override
public void method1() {
}
}
public class Implementation extends AbstractInterface {
@Override
public void method2() {
}
}
See: Java tutorial on abstract classes.
You can create an abstract class which does not implement method2()
public abstract class AbstractImplementation implements interface1 {
public String getVar1() {
// implementation ..
}
public void method1() {
// implementation ..
}
// skip method2
}
Then create multiple implementations:
public class Implementation1 extends AbstractImplementation {
public void method2() {
// implementation 1
}
}
public class Implementation2 extends AbstractImplementation {
public void method2() {
// implementation 2
}
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With