Java class implementing an interface and another class extending this class [closed]
I have an java interface which has few abstract methods.
public interface Interf开发者_JAVA百科ace {
void test();
void test1();
}
Now I have a class A that implements Interface. Requirement is I want to extend class A to multiple client classes. Class A should implement test(). Now I want class A should keep test1 abstract and the implementation of test1 should be done in clients of class A. Is it possible to achieve this in Java. If yes, can somebody correct way to implement this requirement ?
First of all, every method is an interface is public and abstract by default. You have no choice.
Here's how I'd write it, with better names:
public interface A {
void test1();
void test2();
}
public abstract class B implements A {
{
public void test1() { // do something here; concrete implementation }
// Note: Nothing for test2.
// Compiler doesn't complain because it's an abstract class, and this is an abstract method.
}
public class C extends B {
// Note: nothing for test1 - get it from abstract superclass
// Note: compiler will complain if nothing is done to implement test2(), because C isn't abstract
public void test2() { // do something here; concrete implementation }
}
Class C
can override test1()
if it chooses to, but if nothing is done it'll inherit the behavior specified in class B
.
精彩评论