我可以强制传递的对象实现一个或多个接口吗?

时间:2015-07-30 11:30:52

标签: java interface delegates protocols

我正在尝试编写一个依赖于在启动时传递给其构造函数的对象的类。此对象应该是某个抽象基类,并且必须实现在要启动的类中定义的接口。但我不知道这是否可能在Java中。代码看起来像这样:

// The Base class implementing all basic functionality
abstract class A {
    public void letBaseDoSomething() {
        System.out.println("A does something...");
    }
}

// Child class extending A
public class B extends A implements Z_requirements {
    public void letMoreDoSomething() {
        System.out.println("B does something...");
    }
    public Boolean canDoStuff() { /* functionality */}
}

// Now this is the class I want to initiate:
public class Z {
    public interface Z_requirements {
        Boolean canDoStuff();
    }

    public Z(<A implements Z_requirements> base) {
        // PROBLEM
        // This "base" class needs to both extend from the
        // Base class AND implement the Z_requirements interface
        // but apart from defining it in the doc, how do I enforce
        // this in code? This way I can call both:
        base.letBaseDoSomething();
        // and
        base.canDoStuff();
    }
}

如果我没记错的话,在Objective-C中可以指定实现多个&#34;协议的委托对象&#34;这基本上就是接口。

更新

实际上,我可能已经批准了一下......根据下面的建议,我现在如何将T base分配给委托对象,私有Z? E.g:

public class Z<T extends A & Z.Z_requirements> {
    public static interface Z_requirements {/* definition */}
    private T delegate;
    public Z(T base) {
        delegate=base;
    }
}

如果我使用此代码,我总是得到一个&#34;类型安全&#34;警告:

Z z = new Z(class_B_implementing_Z_requirements);

...如果我在构造函数中包含<T>,我会得到一个&#34;类型未定义&#34;错误:

Z<T> z = new Z<T>(class_B_implementing_Z_requirements);

更新

我弄清楚了,因为我误解了类型:

Z<B> z = new Z<B>(class_B_implementing_Z_requirements);

2 个答案:

答案 0 :(得分:4)

您必须使用generics。使用多种类型的type parameter that is bounded声明一个泛型方法:

public static <T extends A & Z_requirements> void doIt(T base) {
    base.letBaseDoSomething();
    base.canDoStuff();
}

或者 - 如果你想在构造函数中执行它 - 你必须以同样的方式约束你的类Z

public class Z<T extends A & Z.Z_requirements> {
    public static interface Z_requirements {
        Boolean canDoStuff();
    }

    public Z(T base) {
        base.letBaseDoSomething();
        base.canDoStuff();
    }
}

答案 1 :(得分:-1)

public interface W { public Boolean canDoStuff() { /* so do it */ } }

public ZZTop extends B implements W
{
  // ...
}

public Z
{
  public Z(ZZtop zztop) {}
}

ZZTop将继承自B,必须从W实现canDoStuff。