【发布时间】:2018-08-23 13:57:46
【问题描述】:
我最初创建了一个接口,其中包含将在两个类之间共享的所有方法,但是,我意识到我希望两个类具有相同的方法,但它们的行为会有所不同。
它们将具有相同的返回类型,但参数不同。我不知道如何实现这一点,或者即使我确实知道如何实现这一点,我也不知道这是否是处理这种情况的正确方法
基本上,我来这里是为了寻找正确的架构方法来完成我想要完成的工作,但我不知道那会是什么。我想我有 4 个问题来确定代码架构:
- 接口是否是正确的方法,如果是,为什么?
- 抽象类是正确的方法吗?如果是,为什么?
- 这似乎是 OOP 的一个共同主题,我的意思是拥有一个函数,你可以在给定特定类的情况下做出不同的行为。代码应该如何设计?
- 最后,我的第一个想法是,“哦,我将只覆盖其中一个类中的方法”,但这让我非常头疼并且无法正常工作。我觉得在尝试覆盖方法时我从来没有遇到过这个麻烦。从接口重写方法是否更复杂?
public interface Character {
public void setAttack();
}
/*the setAttack method here will be set by the programmer. The 3 values
passed by the programmer are then stored into an array*/
public class Player implements Character {
public void setAttack(int x, int y, int z) {
attackArray[0] = x;
attackArray[1] = y;
attackArray[2] = z;
}
}
/*the setAttack will still serve the same purpose as the setAttack in the
player class, however, the values will be auto generated randomly once the
setAttack function is called for the NPC instance.*/
/*Another thought I had is passing the function that auto generates the 3
integer values (numGen()) as a parameter 3 times, however, I'm not sure if
this is possible. Just a thought*/
public class NPC implements Character {
public void setAttack(){
for(int i = 0; i < attackArray.length; i++)
{
attackArray[i] = numGen();
}
}
}
【问题讨论】:
-
//为什么我不能在这里@Override?i>因为参数的数量...
-
你可以
over-load方法setAttack() -
或者也许使它成为 var-args?
setAttack(int.... xyz),取决于用例。 -
如果您需要设计方面的帮助,您需要提供有关类的更多信息——它们的相关属性和方法的实现。
-
@user1803551 我已经编辑了我的代码以提供更多功能细节。你能看一下吗?
标签: java inheritance interface