![](/img/trans.png)
[英]Class A instantiates a Class B instance. How can the Instance of ClassB call a method of class A?
[英]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:未解决的编译问题:无法从类型Portal静态引用非静态方法transport(Agent)
以上是它给我的错误。 我有一个公共类Space,其成员类型为Portal和getPortal()getter。 看起来像:
public class Space {
private String _name;
private String _description;
private Portal _portal;
public Portal getPortal(){
return _portal;
}
}
在我的公共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());
}
}
我的主要问题是使用usePortal()方法工作,Space和Portal类完全起作用。 我不知道如何在Agent类内的Agent实例上调用该方法。
java.lang.Error:未解决的编译问题:无法从类型Portal静态引用非静态方法transport(Agent)
这是因为传输方法是instance
方法,而不是static
方法。
创建一个Portal
实例,然后使用该实例或将transport
方法设为静态
Portal portal = new Portal();
portal.transport(this);
要么
public static void transport (Agent str)
我不知道如何在Agent类内的Agent实例上调用该方法。
代替Agent.this
仅使用this
如果不初始化对象引用,则无法调用其他类方法。 除非声明为静态。
例如:
Portal portal = new Portal();
portal.transport(this);
请注意, this
是对当前对象(在本例中为Agent)的引用。
在线进行更多研究,以了解Java对象如何工作,并研究静态和非静态上下文。 大量的例子!
这应该工作
public void usePortal(){
if(_location.getPortal() != null){
_location.getPortal().transport(this);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.