[英]How can I call a method on an instance within the instance class?
public class Agent {
private Space _location;
private String _name;
public void setLocation(Space space){
_location = space;
}
public void usePortal(){
if(_location.getPortal() != null){
Portal.transport(Agent.this);
}
}
}
java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method transport(Agent) from the type Portal java.lang.Error:未解决的编译问题:无法从类型Portal静态引用非静态方法transport(Agent)
Above is the error it gives me. 以上是它给我的错误。 I have a public class Space with a member variable of type Portal and a getPortal() getter.
我有一个公共类Space,其成员类型为Portal和getPortal()getter。 which looks like:
看起来像:
public class Space {
private String _name;
private String _description;
private Portal _portal;
public Portal getPortal(){
return _portal;
}
}
In my public Portal class, I have a transport method with an Agent parameter: 在我的公共Portal类中,我有一个带有Agent参数的传输方法:
public class Portal {
private String _name;
private String _direction;
private Space _destination;
public Space getDestination(){
return _destination;
}
public void transport(Agent str){
str.setLocation(getDestination());
}
}
My main problem is having the usePortal() method to work, the Space and Portal classes are fully functional. 我的主要问题是使用usePortal()方法工作,Space和Portal类完全起作用。 I don't know how I would call the method on an instance of Agent within the Agent class.
我不知道如何在Agent类内的Agent实例上调用该方法。
java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method transport(Agent) from the type Portal
java.lang.Error:未解决的编译问题:无法从类型Portal静态引用非静态方法transport(Agent)
This is because transport method is an instance
method and not static
. 这是因为传输方法是
instance
方法,而不是static
方法。
Either create an instance of Portal
and then use that or make the transport
method static 创建一个
Portal
实例,然后使用该实例或将transport
方法设为静态
Portal portal = new Portal();
portal.transport(this);
or 要么
public static void transport (Agent str)
I don't know how I would call the method on an instance of Agent within the Agent class.
我不知道如何在Agent类内的Agent实例上调用该方法。
Instead of Agent.this
use just this
代替
Agent.this
仅使用this
You can't call other class methods without initializing an object reference. 如果不初始化对象引用,则无法调用其他类方法。 Unless it is declared static.
除非声明为静态。
For example: 例如:
Portal portal = new Portal();
portal.transport(this);
Note that this
is a reference to the current object, in this case, Agent. 请注意,
this
是对当前对象(在本例中为Agent)的引用。
Do some more research online to see how java objects work and also research static and non-static contexts. 在线进行更多研究,以了解Java对象如何工作,并研究静态和非静态上下文。 Tons of examples!
大量的例子!
this should work 这应该工作
public void usePortal(){
if(_location.getPortal() != null){
_location.getPortal().transport(this);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.