2014-09-26 90 views
-1
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的:未解决的问题编译: 不能使静态参考从类型门户网站如何在实例类中的实例上调用方法?

以上的非静态方法运输(Agent)是它给我的错误。我有一个类型为Portal的成员变量的公共类Space和一个getPortal()getter。它看起来像:

public class Space { 
     private String _name; 
     private String _description; 
     private Portal _portal; 
     public Portal getPortal(){ 
      return _portal; 
     } 
    } 

在我的公开门户类,我有一种运输方式与代理参数:

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()方法来工作,空间和门户类功能齐全。我不知道如何在代理类中的代理实例上调用该方法。

+0

我不明白你的标题。您正在从实例类“Agent”中调用实例方法transport。只需创建一个'Portal'的实例,然后调用'portalInstance.transport(this);'? – 2014-09-26 18:53:31

+0

首先学习'static&this keyword'! – 2014-09-26 18:54:04

回答

1

java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method transport(Agent) from the type Portal

这是因为传输方法是一种instance方法和不static

无论是创建Portal一个实例,然后使用或使transport方法静态

Portal portal = new Portal(); 
portal.transport(this); 

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.this使用只是this

+0

不错的假设跳过静态方法的使用! – 2014-09-26 18:55:00

+0

@WundwinBorn增加了静态方法使用问题 – 2014-09-26 19:01:26

+0

好解释和+1回!无论如何应该与代码一起! – 2014-09-26 19:04:48

1

你可以别叫别的而不需要初始化一个对象引用。除非它被声明为静态。

例如:

Portal portal = new Portal(); 
portal.transport(this); 

注意this是参考当前对象,在这种情况下,代理。

在线进行更多研究,以了解java对象的工作方式,以及静态和非静态上下文的研究。一些例子!

+0

你应该解释'this'关键字! – 2014-09-26 18:57:52

+0

编辑好,打电话。 – proulxs 2014-09-26 19:13:47

0

这应该工作

public void usePortal(){ 
    if(_location.getPortal() != null){ 
    _location.getPortal().transport(this); 
    } 
} 
相关问题