我正在努力重建游戏" The Oregon Trail"并创建了一个对象数组,但无法弄清楚如何在超类中使用这些方法。我有一个超类Location
和子类City
Fort
River
和Landmark
。这是我实例化数组的代码:
City independence = new City("Independence", 102);
River kansas = new River("Kansas", 82);
River bigBlue = new River("Big Blue River", 118);
Fort kearney = new Fort("Fort Kearney", 86);
Landmark chimneyRock = new Landmark("Chimney Rock", 86);
Fort laramie = new Fort("Fort Laramie", 190);
Landmark independenceRock = new Landmark("Independence Rock", 102);
Landmark southPass = new Landmark("South Pass", 57, 125);
River green = new River("Green River", 143);
Fort bridger = new Fort("Fort Bridger", 162);
Landmark sodaSprings = new Landmark("Soda Springs", 57);
Fort hall = new Fort("Fort Hall", 182);
River snake = new River("Snake River", 113);
Fort boise = new Fort("Fort Boise", 160);
Landmark blueMountains = new Landmark("Blue Mountains", 55, 125);
Fort wallaWalla = new Fort("Fort Walla Walla", 120);
Landmark dalles = new Landmark("The Dalles", 100);
kansas.setWidth(620);
kansas.setDepth(4);
bigBlue.setWidth(300);
bigBlue.setDepth(6);
green.setWidth(400);
green.setDepth(20);
snake.setWidth(1000);
snake.setDepth(7);
Object[] locations = new Object[] {
independence,
kansas,
bigBlue,
kearney,
chimneyRock,
laramie,
independenceRock,
southPass,
green,
bridger,
sodaSprings,
hall,
snake,
boise,
blueMountains,
wallaWalla,
dalles
};
类实例化的参数是(字符串名称,到下一个地标的int距离)或(字符串名称,到选项A的int距离,到选项B的距离),因为道路中有叉子。这应该与我的问题无关。
答案 0 :(得分:0)
您想拨打什么方法?
通常,如果您要将一堆对象放在同一个数组或同一个集合中,那是因为您计划在所有上执行一个或多个常用方法(或者,可在任何上执行。)
在这种情况下,你通常会要声明一个interface
来捕捉对象都有的共同点。
在您的示例中,您有Landmark
,Fort
和River
个对象。他们有什么共同点?嗯,首先,他们都有名字。所以你可能有
interface Location {
String getName();
...other methods that apply to all different kinds of location...
}
然后你可能有
class Landmark implements Location {
String getName() { return ...; }
...other methods that apply to all different kinds of location...
...other methods that only apply to Landmarks...
}
class Fort implements Location {
String getName() { return ...; }
...other methods that apply to all different kinds of location...
...other methods that only apply to Forts...
}
etc.
然后,如果你声明你的数组......
Location locations[] = new Location[] { independence, kansas, bigBlue, ...};
编译器允许您将任何Location
方法应用于数组成员。
for (int i=0 ; i<locations.length ; i++) {
System.out.println(locations[i].getName());
}