【问题标题】:How to refer to the variable which is calling the method如何引用调用方法的变量
【发布时间】:2019-03-11 20:36:12
【问题描述】:

假设我有一个示例代码,类似这样

public double {method} ()
{
if (variableThatCalledThisMethod == x)

如何调用调用该方法的变量? (在这种情况下,任何变量都可以调用该方法并且总是不同的)

【问题讨论】:

  • 是什么让你认为 Java 支持这一点?
  • 你的意思是this - 用来调用方法的对象吗?
  • 他的意思是调用该方法的实例。类似 myInstance.method()

标签: java variables methods


【解决方案1】:

您可以使用this 引用访问调用该方法的对象。

class MyClass {
    private double x = 10;
    public double method() {
        if (this.x == 10) {...}
        this.anotherMethod();
        //... 
    }
    public double anotherMethod() {...}
}

查看更多关于this keyword

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多