接口实现隐藏方法

接口实现隐藏方法

本文介绍了接口实现隐藏方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关接口的建议。我有一个名为Unit的类,它可以攻击其他单位。攻击可以是空中或地面。我需要单一方法来实现名为 attack()的攻击。有些单位只能攻击地面单位,某些空中单位或两者。

I need advice on interfaces. I have a class called Unit which can attack other units. The attack can be air or ground. I need single method to achieve attacking called attack(). Some units can only attack ground units, some air units or both.

这是我到目前为止所得到的:

This is what I've come up so far:

public interface Attack() {
    public void attack(SCObject object);
}

public interface GroundAttack() extends Attack {
    public void groundAttack(SCObject object);
}

public interface AirAttack() extends Attack {
    public void airAttack(SCObject object);
}

我可以拥有不同的单位:

I have can have different units:

Unit extends SCObject implements GroundAttack {
}

Unit extends SCObject implements AirAttack {
}

Unit extends SCObject implements AirAttack, GroundAttack {
}

问题在于此实现将显示两个地面和空中选项,而我只希望 attack()方法可见。
你能提出解决方案吗或这对你好吗?

The problem is this implementation will reveal the two ground and air options whereas I only want attack() method to be visible.Can you propose solution or does this seem ok to you?

推荐答案

我会用

public interface Attack {
    public boolean canAttack(SCObject object);
    public void attack(SCObject object);
}

我认为没有理由采用特定的地面或空袭方法鉴于你不想暴露这种行为。

I don't see a reason to have a specific ground or air attack method given you didn't want to expose this behaviour.

这篇关于接口实现隐藏方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:04