简体   繁体   中英

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 . In my Elephant's act() method, I want to use a method ( public List getTurtleList() ), which is found only in World (and AnimalWorld ). 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? 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.

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:

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 . 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.

Maybe you need to implement getTurtleList() in AnimalWorld , or in Elephant .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM