从其他类调用方法java [英] Calling methods from other classes java

查看:154
本文介绍了从其他类调用方法java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始用Greenfoot编程一些东西,一路上学习java。我已经熟悉如何调用类之间的某些方法,以及静态和非静态之间的差异。



我正在做一个游戏,你玩螃蟹和移动收集蠕虫。有一个龙虾随机漫游,如果与螃蟹接触,螃蟹消失。每次你吃一个蠕虫,得分上升10。



它包含5个类名为螃蟹,龙虾,蠕虫,柜台和CrabWorld。为了您的缘故,我会发布良好的文档代码供您阅读。但是我遇到麻烦的重要部分是调用一个方法从龙虾到Crab世界创建的Crab实例。这种方法会改变螃蟹的生命。



我试过调用((CrabWorld)getWorld),但我不需要访问CrabWorld。我需要访问来自龙虾类的Crab实例(在CrabWorld中创建的)。



Crabworld:

  import greenfoot。 //(世界,演员,GreenfootImage,Greenfoot和MouseInfo)

/ **
*用计数器,螃蟹和龙虾创建螃蟹环境。还有方法
*放置随机蠕虫在世界上随着时间的推移。还有一个方法来添加分数
*到计数器分数
* @author Troy Bick
* @version 12/20/13
* /
public class CrabWorld扩展世界
{
private Actor playerCrab = new Crab();
private Counter score = new Counter(Score:);

/ **
* CrabWorld类的对象的构造方法。
*
* /
public CrabWorld()
{
super(560,560,1)

prepare();
}

/ **
*为程序的开始做好准备。这是:创建初始
*对象并将它们添加到世界。
* /
private void prepare()
{
addObject(score,100,540);

addObject(playerCrab,280,280);
addObject(new Lobster(),100,100);
}

/ **
*随机地将蠕虫置于随机周期
* /
public void act()
{
if(Greenfoot.getRandomNumber(100)<0.5){
addObject(new Worm(),Greenfoot.getRandomNumber(540)+10,Greenfoot.getRandomNumber(540)+10);
}
}

public void eatenWorm()
{
score.add(10);
}

public void eatsCrab()
{
playerCrab.isEaten();
}

螃蟹:

  import greenfoot。*; //(World,Actor,GreenfootImage,Greenfoot和MouseInfo)

public class Crab extends Actor
{
private int wormsEaten = 0;
private int lives = 3;

/ **
* Act - 做任何Crab想做的事情。当在环境中按下
*'Act'或'Run'按钮时,调用此方法。运行调用执行每
*框架。
* /
public void act()
{
moveAndTurn();
eat();
}

/ **
*确定按下的键并移动/旋转螃蟹。
* /
public void moveAndTurn()
{
move(3);
if(Greenfoot.isKeyDown(a)){
turn(3);
}
if(Greenfoot.isKeyDown(d)){
turn(-3);
}
}

/ **
*检测蠕虫是否接近螃蟹,如果是这样,就吃它。
* /
public void eat()
{
Actor worm;
worm = getOneObjectAtOffset(0,0,Worm.class);

世界world = getWorld();

if(worm!= null)
{
world.removeObject(worm);
Greenfoot.playSound(eating.wav);
wormsEaten ++;
((CrabWorld)getWorld())。eatenWorm();
}
}

/ **
*返回被吃的蠕虫数。
* /
public int getWormsEaten()
{
return wormsEaten;
}

/ **
*返回crab剩下的生命数。
* /
public int getLivesCount()
{
return life;
}


/ **
*从生命中减去生命。
* /
public void eaten()
{
lives--
}
}

龙虾:

  import greenfoot。 //(World,Actor,GreenfootImage,Greenfoot and MouseInfo)

/ **
*在这里写一个关于龙虾类的描述。
*
* @author(您的姓名)
* @version(版本号或日期)
* /
public class Lobster extends Actor
{
/ **
*法案 - 做任何龙虾想做的事。当在环境中按下
*'Act'或'Run'按钮时,调用此方法。
* /
public void act()
{
moveAround();
eat();
}

public void eat()
{
Actor crab;
crab = getOneObjectAtOffset(0,0,Crab.class);
if(crab!= null)
{
世界world = getWorld();
world.removeObject(crab);
((CrabWorld)getWorld())。eatsCrab();
}
}

public void moveAround()
{

move(3);

//随机移动
if(Greenfoot.getRandomNumber(100)< 10)
{
turn(Greenfoot.getRandomNumber(40) - 20);
}

//世界边缘检测
if(getX()<= 10 || getX()> = getWorld()。getWidth() - 10)
{
turn(10);
}
if(getY()<= 10 || getY()> = getWorld()。getHeight() - 10)
{
turn
}
}
}

添加到世界吃螃蟹,我想让螃蟹失去一生,但是当我尝试编译,我得到一个错误的CrabWorld类,它找不到所提到的方法。为什么呢?



只是很困惑...如果有人能帮助我,那将是伟大的。如果我遗漏了什么,我修复它。



感谢高级,
Troy

解决方案

问题是你在 CrabWorld 中声明 playerCrab

  private Actor playerCrab = new Crab(); 

所以虽然playerCrab实际上是一个Crab的实例,但CrabWorld它是一个Actor,调用Actor定义的方法。



您可以将声明更改为

  private Crab playerCrab = new Crab(); 



这样CrabWorld知道 playerCrab Crab 的实例,然后可以调用 Crab 定义的任何公共方法。假设你的成员变量叫做 playerCrab ,你会总是把它作为 Crab ,所以

另一种方法是,如果你控制 Actor 类型,如果你认为丢失生命的概念对于扩展 Actor 的类是常见的,请添加 lossLife() >。你的 Lobster 类目前没有这个概念,但如果你决定添加它,那么 Actor 是一个合适的方式。


I have just started programming some things with Greenfoot, learning java along the way. I have become familiar on how to call certain methods between classes, and also differences between static and non-static.

I'm makeing a game where you play the crab and move around to collect worms. There is a lobster that randomly roams around and if comes in contact with the crab, the crab dissapears. Every time you eat a worm, the score goes up by 10.

It contains 5 classes named Crab, Lobster, Worm, Counter, and CrabWorld. For your sake, I'll just post the well documented code for you to read. But the important part that I am having trouble with is calling a method from the lobster to the Crab instance created by the CrabWorld. This method would change the lives of the crab.

I have tried calling ((CrabWorld) getWorld), but I don't need to access the CrabWorld. I need to access the Crab instance (created in the CrabWorld, if that matters) from from the Lobster Class.

Crabworld:

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Creates the crab Enviornment with a counter, crab and lobster.  Also has methods to
 * place random worms in the world over time.  Also has a method to add the score 
 * To the Counter score
 * @author Troy Bick 
 * @version 12/20/13
 */
public class CrabWorld extends World
{
    private Actor playerCrab = new Crab();
    private Counter score = new Counter("Score: ");

    /**
    * Constructor for objects of class CrabWorld.
    * 
    */
    public CrabWorld()
    {    
        super(560, 560, 1); 

        prepare();
    }

    /**
     * Prepare the world for the start of the program. That is: create the initial
     * objects and add them to the world.
     */
    private void prepare()
    {
        addObject(score, 100, 540);

        addObject(playerCrab, 280, 280);
        addObject(new Lobster(), 100, 100);
    }

    /**
     * Randomly places worms at random periods
     */
    public void act()
    {
        if(Greenfoot.getRandomNumber(100)<0.5){
            addObject(new Worm(), Greenfoot.getRandomNumber(540)+10,                    Greenfoot.getRandomNumber(540)+10);
        }
    }

    public void eatenWorm()
    {
        score.add(10);
    }

    public void eatsCrab()
    {
        playerCrab.isEaten();
}

Crab:

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Crab extends Actor
{
    private int wormsEaten = 0;
    private int lives = 3;

    /**
     * Act - do whatever the Crab wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.  Run calls Act every
     * frame.
     */
    public void act() 
    {
       moveAndTurn();
       eat();
    }

    /**
     * Determines the key pressed and moves/turns the crab.
     */
    public void moveAndTurn()
    { 
        move(3);
        if(Greenfoot.isKeyDown("a")){
            turn(3);
        }
        if(Greenfoot.isKeyDown("d")){
            turn(-3);
        }
    }

    /**
     * Detects if the worm is close to the crab, and if so, eats it.
     */
    public void eat()
    {
        Actor worm;
        worm = getOneObjectAtOffset(0,0,Worm.class);

        World world = getWorld();

        if(worm != null)
        {
            world.removeObject(worm);
            Greenfoot.playSound("eating.wav");
            wormsEaten++;
            ((CrabWorld) getWorld()).eatenWorm();
        }
    }

    /**
     * Returns the number of worms eaten.
     */
    public int getWormsEaten()
    {
        return wormsEaten;
    }

    /**
    * Returns the number the lives the crab has left.
    */
    public int getLivesCount()
    {
        return lives;
    }


    /**
    * Subtracts a life from lives.
    */
    public void eaten()
    {
        lives--;
    }
}

Lobster:

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Lobster here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Lobster extends Actor
{
    /**
     * Act - do whatever the Lobster wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
    */
    public void act() 
    {
        moveAround();
        eat();
    }

    public void eat()
    {
        Actor crab;
        crab = getOneObjectAtOffset(0,0,Crab.class);
        if(crab != null)
        {
            World world = getWorld();
            world.removeObject(crab);
            ((CrabWorld) getWorld()).eatsCrab();
        }
    }

    public void moveAround()
    {

        move(3);

        //Random Movements
        if(Greenfoot.getRandomNumber(100) < 10)
        {
            turn(Greenfoot.getRandomNumber(40) - 20);
        }

        //World Edge Detection
        if(getX() <= 10 || getX() >= getWorld().getWidth()-10)
        {
            turn(10);
        }
        if(getY() <= 10 || getY() >= getWorld().getHeight()-10)
        {
            turn(10);
        }
    }
}

So when the lobster that has be added to the world eats the crab, I want that crab to lose a life, but when I try to compile, I get an error on the CrabWorld class that it could not find the method mentioned. Why is that?

Just very confused... If anyone could help me that would be great. If I'm missing anything, I fix it.

Thanks in advanced, Troy

解决方案

The problem you have is that in CrabWorld you declare playerCrab as

private Actor playerCrab = new Crab();

So although playerCrab is actually an instance of Crab, to CrabWorld it is an Actor and you can therefore only call the methods that Actor defines.

You could change your declaration to

private Crab playerCrab = new Crab();

That way CrabWorld knows that playerCrab is an instance of Crab and you can then call any of the public methods that Crab defines. Given that your member variable is called playerCrab it seems that you will always have it as a Crab, so there it's certainly appropriate for it to be declared as one.

An alternative approach, if you control the Actor type would be to add a loseLife() method to it if you think that the concept of losing a life is common to classes that extend Actor. Your Lobster class doesn't have that concept at present, but if you were to decide to add that to it then a method on Actor would be an appropriate way to do it.

这篇关于从其他类调用方法java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆