0

Is it possible in java to inherit some methods from the base class, but not all of them? Just to be clear, i will show you what I mean: Suppose we have the base class Visitor

public abstract class Visitor {}

From Visitor we create 2 more Objects, Client and Companion:

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

In Client, we create the method:

boolean has_Companion() {}

In order to achieve runtime polymorphism, we need to declare the method in Visitor as well:

abstract boolean has_Companion();

The problem is that since we declare the method in Visitor, Companion inherits it as well. We don't want that. When I compile I get the following error:

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

There is no point in implementing the method has_Companion() for Companion because it will never be used. It's a waste of code. Can I avoid it in some way? Can the method has_Companion() be inherited only by Client, and not by Companion?

4

1 回答 1

0

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

想法 1:有Companion覆盖hasCompanion并且总是返回false

想法 2Visitor提供一个hasCompanion简单地总是返回的实现false。然后客户端将覆盖hasCompanion实际逻辑以确定客户端是否有同伴。

想法3:根本不给hasCompanion方法Visitor,而只在Client. 然后代码通过运算符进行运行时类型检查,并通过强制转换instanceof调用方法。Client例子:

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

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

想法 4:重新考虑设计并重构类型树以及代码如何使用继承。如果调用hasCompanionon没有任何意义Companion extends Visitor,那为什么是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根据需要进行更改。很清楚哪些方法属于哪些类型。毫无疑问,在较大的项目中,执行此操作的工作量会扩展,但它可能会导致代码更简洁。

于 2019-01-06T19:54:18.870 回答