[英]How can I use a method in a different class?
I'm working on a project, and I need some help here. 我正在做一个项目,在这里我需要一些帮助。 I have an
AnimalWorld
that extends World
, and an Elephant
class that extends Turtle
. 我有一个
AnimalWorld
来扩展World
,还有一个Elephant
类来扩展Turtle
。 In my Elephant's act()
method, I want to use a method ( public List getTurtleList()
), which is found only in World
(and AnimalWorld
). 在我的Elephant的
act()
方法中,我想使用仅在World
(和AnimalWorld
)中找到的方法( public List getTurtleList()
)。 I've tried addiding the line 我试过加线
public abstract List<Turtle> getTurtleList();
to AnimalWorld, and set Elephant to an abstract class, but I still get the error 'cannot find symbol - getTurtleList()
Any thoughts? 到AnimalWorld,并将Elephant设置为抽象类,但是我仍然收到错误消息“找不到符号
getTurtleList()
什么想法? If you need more info, just let me know. 如果您需要更多信息,请告诉我。 Also, Elephant does not extend AnimalWorld, as the elephants created are to be placed in the AnimalWorld.
同样,Elephant不会扩展AnimalWorld,因为创建的大象将放置在AnimalWorld中。
public abstract class Elephant extends Turtle implements Animal{
public Elephant(ModelDisplay world){
super(world);
this.penUp();
this.setColor(Color.gray);
this.setWidth(50);
this.setHeight(50);
}
public void act(ModelDisplay myWorld){
double smallestDist = 640.0;
Mouse closestMouse = null;
List<Turtle> animalList = myWorld.getTurtleList();
for(Turtle curCritter: animalList){
if(curCritter instanceof Mouse){
int x=curCritter.getXPos();
int y=curCritter.getYPos();
double dist = this.getDistance(x,y);
if(dist < 100 && dist<smallestDist){
closestMouse=curCritter;
smallestDist=dist;
}
}
}
if(closestMouse!=null){
this.turn(closestMouse);
this.forward(3*(int)smallestDist);
}
}
}
Declaring World
class as: 宣布
World
一流为:
public abstract class World{
...
public abstract List<Turtle> getTurtleList();
}
will force you to implement a method called getTurtleList()
in every class that inherits from World
. 将迫使您在从
World
继承的每个类中实现一个名为getTurtleList()
的方法。 If not, you will be forced to declare the subclass also as abstract. 如果没有,您将不得不将子类也声明为抽象的。 That's why you are forced to declare
Elephant
as an abstract class, because it doesn't implement all abstract methods from superclass. 这就是为什么您不得不将
Elephant
声明为抽象类的原因,因为它不能实现超类的所有抽象方法。
Maybe you need to implement getTurtleList()
in AnimalWorld
, or in Elephant
. 也许您需要在
AnimalWorld
或Elephant
实现getTurtleList()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.