继承 java 中的特定方法

Inheriting specifid methods in java

是否可以在 java 中继承基础 class 的一些方法,但不是全部?为了清楚起见,我将向您展示我的意思: 假设我们有基础 class 访客

public abstract class Visitor {}

我们从访客创建了另外 2 个对象,客户和伴侣:

public class Client extends Visitor {}
public class Companion extends Visitor {}

在客户端中,我们创建方法:

boolean has_Companion() {}

为了实现运行时多态,我们还需要在Visitor中声明方法:

abstract boolean has_Companion();

问题是因为我们在Visitor中声明了这个方法,Companion也继承了它。我们不想要那样。编译时出现以下错误:

The type Companion must implement the inherited abstract method Visitor.has_Companion()

为 Companion 实现 has_Companion() 方法没有意义,因为它永远不会被使用。这是浪费代码。我能以某种方式避免它吗?方法has_Companion()只能被Client继承,Companion不能继承吗?

简短的回答是 Java 不支持您尝试做的事情,但好消息是有很多方法可以解决它。

想法 1:让 Companion 覆盖 hasCompanion 并且总是 return false.

想法 2:让 Visitor 提供一个 hasCompanion 的实现,它总是 return false。然后 Client 将用实际逻辑覆盖 hasCompanion 以确定 Client 是否有同伴。

想法3:根本不要给Visitor一个hasCompanion方法,而是只给Client一个方法.然后代码通过 instanceof 运算符进行 运行 时间类型检查,并通过转换调用 Client 上的方法。示例:

if (visitor instanceof Client) {
    Client client = (Client) visitor;
    boolean hasCompanion = client.hasCompanion();
    // other logic
}

这充其量只是虚假的多态性,是一个非常笨拙的解决方案。如果可能的话,我建议不要这样做。

思路4:重新考虑设计重构类型树以及代码如何使用继承。如果在 Companion extends Visitor 上调用 hasCompanion 没有意义,为什么 hasCompanion 根本就是 Visitor 的方法?

Java不支持多重继承,所以需要接口:

public interface MightHaveCompanion {
    public boolean hasCompanion();
}

public abstract class Visitor {
    // methods that all Visitors must have
}

public class Client extends Visitor implements MightHaveCompanion {
    // overriding implementations of MightHaveCompanion and Visitor methods 
}

public class Companion extends Visitor {
    // overriding implementations of Visitor methods
}

然后调用代码必须根据需要更改为使用类型 MightHaveCompanionVisitor。什么方法属于什么类型一目了然。毫无疑问,在较大的项目中,执行此操作的工作量会增加,但这可能会导致代码更清晰。