[英]Call a method in another class
I have a class called Ball, and i want to call a method called update in a class called MagicBallImage. 我有一个名为Ball的类,我想在一个名为MagicBallImage的类中调用一个名为update的方法。 Below is the method isVisible() in the Ball class, from which I am trying to call the method update, but I am getting an error saying:
下面是Ball类中的isVisible()方法,我试图从该方法中调用方法update,但出现一条错误消息:
Ball.java:58: non-static method update() cannot be referenced from a static context.
MagicBallImage.update();
Ball Class
public boolean isVisible()
{
if (magicBallState != 1)
{
return true;
MagicBallImage.update();
}
}
Anyone know how to solve this? 有人知道如何解决吗?
It's telling you that you're trying to call a non-static method without a class instance. 它告诉您,您正在尝试在没有类实例的情况下调用非静态方法。 You either need an instance of
MagicBallImage
to call the method on, or you need to convert the method to static
. 您或者需要一个
MagicBallImage
实例来调用该方法,或者需要将该方法转换为static
。
if (magicBallState != 1)
{
return true;
MagicBallImage.update();
}
you're returning before you call update, so it will have no effect 您在致电更新之前要返回,因此它不会起作用
update()
is not a static method
, so you can't call it from a static context. update()
不是static method
,因此您不能从静态上下文中调用它。 You can simply call update()
or this.update()
if you're already in object scope, or call o.update()
where o
is your object. 如果您已经在对象范围内,则可以简单地调用
update()
或this.update()
,或者调用o.update()
,其中o
是您的对象。
This error tells you that you cannot call update without specifying an instance of MagicBallImage
. 此错误告诉您,如果不指定
MagicBallImage
实例 ,则无法调用update。
Two things could have happened: 可能发生了两件事:
MagicBallImage.update()
method static
, or MagicBallImage.update()
方法设置为static
,或者 MagicBallImage
that you created somewhere using the new
operator available to your isVisible()
method. isVisible()
方法可用的new
运算符来创建在某个位置创建的MagicBallImage
实例。 Note 1: The way it is coded now, MagicBallImage.update()
is not accessible, because it comes after the return
statement. 注意1:现在无法使用
MagicBallImage.update()
编码,因为它位于return
语句之后。
Note 2: It is very undesirable for a getter isVisible
to have side effects, such as updating something in an instance of another class. 注意2:让
isVisible
具有副作用,例如在另一个类的实例中更新某些内容,这是非常不希望的。 It is a nearly 100% indication that something is wrong with your design. 这几乎是100%的迹象表明您的设计有问题。
If you want to call this method like this, the method has to be declared static
. 如果要这样调用此方法,则必须将该方法声明为
static
。 If it's not you have to declare an instance of MagicBallImage
to access update()
: 如果不是,则必须声明一个
MagicBallImage
实例才能访问update()
:
MagicBallImage mbi = new MagicBallImage();
mbi.update();
使update()方法为静态,或创建MagicBallImage的实例并调用update()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.