首页 > 解决方案 > parameter.method 或 argument.method 怎么可能?我认为它总是class.method。有人可以解释吗?

问题描述

我是java新手,我总是被教导它总是class.method,现在这个有another.getX的代码让我很困惑。我从来没有意识到 parameter 或 argument.method 是可能的 有人可以解释它是如何工作的吗?

public class Point {
private int x;
private int y;

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}

public Point() {
    this(0,0);
}

public Point(int x, int y) {
    this.x = x;
    this.y = y;
}

public double distance (){


    double distance = Math.sqrt((x - 0) * (x - 0) + (y - 0) * (y - 0));

   return distance;
}

public double distance (int x, int y){

    double distance = Math.sqrt((x-this.x) * (x-this.x) + (y-this.y) * (y - this.y));
    return distance;
}

public double distance (Point another){

    double distance =  Math.sqrt((another.x - x)   * (another.x - x) + (another.y - y)   * (another.y - y));
    return distance;
}

}

标签: java

解决方案


有可能的。

与往常一样,Java 语言规范第 15.1 节中对它进行了很好的定义。这是一个节选:

如果表达式表示一个变量,并且在进一步评估中需要一个值,则使用该变量的值。在这种情况下,如果表达式表示变量或值,我们可以简单地说表达式的值。

这意味着someObject.someMethod()可能会产生具有结果类型的值。

这是一个例子:

class A {
    B getB() {
        return new B();
    }
}
class B {
    C getC() {
        return new C();
    }
}
class C {
    String getString() {
        return "Hello World!";
    }
}

您可以像这样“链接”您的方法调用:

A myA = new A();
String str = myA.getB().getC().getString().toUpperCase();
System.out.println(str); // Prints "HELLO WORLD!"

会发生什么:

  • myA是一个A
  • A.getB()返回一个B
  • B.getC()返回一个C
  • C.getString()返回一个String
  • String.toUpperCase() returns aString , thus the final result is aString , which is stored into thestr` 变量。

还有一些注意事项:SomeClass.someMethod()表示静态方法。如果当前类是 ,则可以省略类名SomeClasssomeVariable.someMethod()但是,它是一个实例方法,它只能在实例上调用。


推荐阅读