简体   繁体   English

在先前方法(Java)中实例化的对象上的调用方法

[英]Calling methods on an object instantiated in a previous method (Java)

To put it simply, I have the following code: 简单来说,我有以下代码:

public void dance()
{
CartoonFigure dancer = new CartoonFigure("rico", 300, 300);
danceStepTwo();
danceStepOne();
}

public void danceStepOne()
{
    dancer.turnLeft();
}

public void danceStepTwo()
{
   dancer.turnLeft();
}

but calling these methods on the dancer object give me a compile error 'cannot find symbol - variable dancer.' 但是在舞者对象上调用这些方法会给我一个编译错误“找不到符号-变量舞者”。 How can I fix this so I can call methods of the dancer object from danceStepOne() ? 如何解决此问题,以便可以从danceStepOne()调用舞者对象的方法?

Define dancer as an instance variable so that it becomes available to both the methods. 将舞者定义为实例变量,以便它对两种方法均可用。 Else pass its instance to both the methods. 否则将其实例传递给这两种方法。

Declare dancer as a field variable. dancer声明为字段变量。 Put it (on top) outside any method along with a scope declaration, eg private CartoonFigure dancer . 将其(在顶部)与范围声明一起放在任何方法之外,例如, private CartoonFigure dancer

You will have to make dancer global, and this error is due to the fact that it's only visible to the method dance() , make it an instance field as follows. 您将必须使dancer全局对象,并且此错误是由于以下事实导致的:仅对dance()方法可见,使它成为实例字段,如下所示。

private CartoonFigure dancer;

Initializing it can be done in the constructor as follows 可以在构造函数中进行如下初始化

dancer = new CartoonFigure("rico", 300, 300);

As "dancer" object is unavailable for "danceStepOne" and "danceStepTwo", it cannot recognize and will give compilation failure. 由于“ danceStepOne”和“ danceStepTwo”无法使用“跳舞者”对象,因此无法识别并且将导致编译失败。

For this, any of solution will work 为此,任何解决方案都可以使用

  1. Pass it as variable to the method 将其作为变量传递给方法
  2. Declare "dancer" as global variable 将“ dancer”声明为全局变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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