如何引用既扩展又实现的实例?

时间:2016-05-31 13:40:51

标签: java inheritance interface

我们说我有一个抽象类,一个扩展类和一个这样的接口:

public abstract class SuperClass {
    ...
    public void foo() {...}
    ...
}

public class SubClass extends SuperClass implements MyInterface {...}

public interface MyInterface {
    public void bar();
}

请注意,我有几个实现MyInterface的SuperClass子类,但不是全部。 还可以说,我有另一个类,有这样的构造函数:

public class AnotherClass {
    private SuperClass sc;
    public AnotherClass(SuperClass superclass) {
        sc = superclass;
    }
    ...
}

我现在的问题是,如何确保构造函数中的给定对象也实现MyInterface?我需要对象sc才能运行方法foo()bar()。我怎么能做到这一点?

3 个答案:

答案 0 :(得分:3)

您可以将generics与交叉类型

一起使用
public class AnotherClass<T extends SuperClass & MyInterface> {
private T sc;
public AnotherClass(T superclass) {
    sc = superclass;
}
void fn(){
 // use both methods
 sc.foo();
 sc.bar();
}
...
}

现在,AnotherClass只允许SuperClass类型并实施MyInterface

答案 1 :(得分:3)

你可以在层次结构中引入另一个类:

public class NonImplementingSubClass extends SuperClass {...}

public class ImplementingSubClass extends SuperClass implements MyInterface {...}

应该实现接口的所有子类将扩展ImplementingSubClass

public class SubClass extends ImplementingSubClass {...}

public class AnotherClass {
    private ImplementingSubClass sc;
    public AnotherClass(ImplementingSubClass superclass) {
        sc = superclass;
    }
    ...
}

答案 2 :(得分:0)

public abstract class SuperClass implements MyInterface {
    ...
    public void foo() {...}
    ...
}

public class SubClass extends SuperClass{}

public interface MyInterface {
    public void bar();
}