开发者

extend/inherit from 2 classes in Java

I've read up on this topic and it seems my best option is to make one of the classes that I want to extend into an interface..

The thing is that ParentA is a class from the Android API, so I can't actually modif开发者_开发技巧y it (I only have the build), and ParentB was made by a friend, ParentB already implements Runnable (and AFAIK you can't have an interface that implements another interface.. I get errors anyway).


You can't have an interface that implements another interface, since interfaces have nothing to do with implementation. You can, however, have an interface that extends another interface. You can also have a class that implements two different interfaces.

When you have two potential parents for your subclass and they don't subclass each other, the thing you need to ask yourself is whether your class isa ParentA or isa ParentB. Which one fits better? Once you decide that, you turn the other one into a hasa.

So let's say that you decide your class isa ParentA. Your code could look something like:

public class MyClass extends ParentA {

    private final ParentB runnable;
    private final Thread runningThread;

    public MyClass(ParentB runnable) {
        this.runnable = runnable;
        this.runningThread = new Thread(this.runnable);
    }

    public void start() {
        this.runningThread.start();
    }

    public void interrupt() {
        this.runningThread.interrupt();
    }

    public boolean isAlive() {
        return this.runningThread.isAlive();
    }
}

Here I am delegating thread methods rather than ParentB methods, since that is what you will most likely want to control on a Runnable. If ParentB has its own behaviour that you want to expose, then you will need delegation methods for those as well.


In Java you can extend interfaces.

But for your case I would suggest using a aggregation pattern or a delegation pattern.

Take a look at the Java Design patterns: http://en.wikipedia.org/wiki/Delegation_(programming)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜