简体   繁体   English

有效的Java项目19-仅使用接口定义类型

[英]Effective Java item 19- only using interfaces to define types

I have an abstract class which implements two interfaces. 我有一个实现两个接口的抽象类。 Am I right in thinking Because I use two interfaces, I cannot use either interface to implement dynamic binding? 我在考虑正确吗,因为我使用两个接口,所以不能使用这两个接口来实现动态绑定? Reason being if I were to use one of the interfaces, I would obviously not be able to invoke methods from the other interface as the type system would only allow the sub type to invoke methods defined by the interface I used to declare the polymorphic variable? 原因是如果我要使用其中一个接口,那么我显然将无法从另一个接口调用方法,因为类型系统将仅允许子类型调用由我用来声明多态变量的接口定义的方法?

Therefore, my actual question is it ok that I am only really using the interfaces to ensure my abstract class (or the subclasses) definitely provide an implementation for the methods? 因此,我的实际问题是可以只使用接口来确保抽象类(或子类)确实提供方法的实现吗? This seems to contradict what Item 19 states- you should only use interfaces for types (I took that to mean polymorphism). 这似乎与第19项所说的相矛盾-您应该只对类型使用接口(我认为这是指多态)。

Example: 例:

public interface A{
    public void meth1();
}

public interface B{
    public void meth2();
}

public abstract class C implements A,B{

}

public void DynamicBinding(A aobject){
  //Can only call aobject.meth1();
}

You can use generics to have your method take a parameter of both type A and B: 您可以使用泛型来让您的方法采用A型和B型参数:

public <T extends A & B> void method(T param) {
  param.meth1(); // fine
  param.meth2(); // also fine
}

Related question here 相关问题在这里

When you need methods from only A then A can be used as an object's type as you have illustrated. 当您只需要A方法时, A可以用作您所说明的对象的类型。 Similarly for B . 对于B同样。 If you need methods from both, you make make a new interface: 如果两种方法都需要,则创建一个新接口:

public interface C extends A, B {
}

Interfaces are allowed to extend more than one interface. 允许接口extend多个接口。

Then you can add an abstract class with default implementations, if you wish: 然后,您可以根据需要添加具有默认实现的抽象类:

public abstract class D implements C {
  // implementation details
}

You could do 你可以做

public void DynamicBinding(C cobject){
  c.meth1();
  c.meth2();
}

or little worse variant 或更差的变体

public void DynamicBinding(A aobject){
if(aobject instanceof C)
      {
          C myC=(C)aobject;
          myC.meth1();
          myC.meth2();

      }
}

anyway I like what Jorn did better. 无论如何,我喜欢乔恩做得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM