您有没有办法在两个不同的类之间使用相同的add()方法(在数组中添加内容)?例如,我的湖类具有以下add()方法:
public void add (Fish aCatchableThing)
{
if (numThings < catchableThings.length)
{
catchableThings[numThings++] = aCatchableThing;
}
}
我试图使用以下代码:
public class FishingTestProgram3
{
public static void main(String [] args)
{
Lake weirdLake = new Lake(21);
weirdLake.add(new AuroraTrout(76, 6.1f));
weirdLake.add(new Tire());
weirdLake.add(new Perch(32, 0.4f));
weirdLake.add(new Bass(20, 0.9f));
weirdLake.add(new Treasure());
weirdLake.add(new Perch(30, 0.4f));
weirdLake.add(new AtlanticWhiteFish(140, 7.4f));
weirdLake.add(new RustyChain());
weirdLake.add(new Bass(15, 0.3f));
weirdLake.add(new Tire());
这将起作用(使用继承,即EndangeredFish extends fish, and Perch extends EndangeredFish )
为所有添加的鱼但是它不起作用的对象(即Tire,RustyChain,Treasure).Tire,RustyChain和Treasure是扩展SunkenObject的类字面上空的类:
public abstract class SunkenObject
{
}
我尝试在湖类中创建第二个添加方法但是没有成功。我想知道是否有人对这如何运作有任何想法?我可以将所有东西(例如鱼和沉没对象)添加到同一个数组中,以便在
时public void listAllThings()
{
System.out.println(" " + this + " as follows:");
for (int i=0; i<numThings; i++)
{
System.out.println(" " + catchableThings[i]);
System.out.println();
}
实现数组中的所有内容打印出来。谢谢你的帮助
如果有人想知道这是我试过的add()方法
public void add (SunkenObject sunkenObject)
{
if (numThings < catchableThings.length)
{
catchableThings[numThings++] = sunkenObject;
}
}
答案 0 :(得分:5)
答案几乎就在问题中。您希望能够添加到湖中的不仅仅是Fish
的实例。你想要添加的是一个可捕获的东西。所以你需要定义这样的类型。
Fish
和SunkenObject
应扩展名为CatchableThing
的公共基类,或者应实现名为CatchableThing
的接口。
add()
方法的签名应为
public void add(CatchableThing aCatchableThing)
答案 1 :(得分:2)
考虑编程到接口而不是具体类型 - 例如ICatchable
:
public void add(ICatchable item)
{
// Add the catchable item to the lake.
}
答案 2 :(得分:0)
创建一个公共基类,从中可以派生您想要添加的所有内容。