开发者

Java class implementing an interface and another class extending this class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜