在接口中添加新方法时如何排除所有类

yas*_*sin 1 java methods abstract implements

我有接口,抽象方法,并且有更多分类,并在下面使用这些引用类型。

   public interface InterfaceA {
    boolean mehod1();
    boolean method2();
    boolean newMethod(); //When added new method  
    }

public abstract class AbstractA implements InterfaceA{
// other common method

}


public Class C extend AbstractA //have to override three method
public Class D extend AbstractA //have to override three method
public Class E extend AbstractA //have to override three method but only should be override old method
public Class F extend AbstractA  //have to override three method  but only should be override old method
Run Code Online (Sandbox Code Playgroud)

这些类派生了AbstractA类,我只想在接口中使用新方法,而仅实现C和D类,其他则应仅使用旧方法。

应该如何设计?

Kav*_*ran 5

您可以通过两种方式处理它:

  1. 如果您使用的是Java 7或更低版​​本,请扩展InterfaceA以创建一个新接口
    public InterfaceB extends InterfaceA{
    // Your new methods definitions here..
    }
Run Code Online (Sandbox Code Playgroud)

让C和D类实现InterfaceB。

  1. 如果使用的是Java 8或更高版本,请按照@Slaw的建议,将默认方法添加到InterfaceA。覆盖默认实现以在C和D类中提供自定义实现