【问题标题】:How can I call a method on an instance within the instance class?如何在实例类中调用实例上的方法?
【发布时间】:2014-11-21 20:44:46
【问题描述】:
    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;
        }
    }

在我的公共门户类中,我有一个带有代理参数的传输方法:

    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 实例上的方法。

【问题讨论】:

  • 我不明白你的标题。您正在从实例类Agent 调用实例方法transport。只需创建Portal 的实例,然后调用portalInstance.transport(this);?
  • 先学习static & this keyword!!

标签: java methods instance-variables


【解决方案1】:

你不能在没有初始化对象引用的情况下调用其他类方法。除非它被声明为静态的。

例如:

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

请注意,this 是对当前对象的引用,在本例中为 Agent。

在网上做更多的研究,看看 java 对象是如何工作的,同时研究静态和非静态上下文。大量的例子!

【讨论】:

  • 你也应该解释this关键字!!
【解决方案2】:

这应该可以工作

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

【讨论】:

    【解决方案3】:

    java.lang.Error:未解决的编译问题:无法制作静态 从类型中引用非静态方法 transport(Agent) 传送门

    这是因为传输方法是instance 方法而不是static

    要么创建Portal 的实例然后使用它,要么将transport 方法设为静态

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

    public static void transport (Agent str)
    

    我不知道如何调用 Agent 实例上的方法 在 Agent 类中。

    只使用this 而不是Agent.this

    【讨论】:

    • 不错的假设跳过了静态方法的使用!!
    • @WundwinBorn 也添加了静态方法使用问题
    • 很好的解释和+1回!!无论如何应该发布代码!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 2016-08-30
    • 2015-06-10
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多