java - 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 语言规范第 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 a
String, thus the final result is a
String, which is stored into the
str` 变量。
还有一些注意事项:SomeClass.someMethod()
表示静态方法。如果当前类是 ,则可以省略类名SomeClass
。someVariable.someMethod()
但是,它是一个实例方法,它只能在实例上调用。
推荐阅读
- r - 根据给定值通过 ID 更改数据集中的观察次数
- python - 我可以在不更改 django 应用程序的情况下使用 FastAPI 扩展我的 Django 项目吗?
- visual-studio-code - 运行 Web 项目时的 Visual Studio Code 隐身模式
- sql - 使用 json 对象更新 SQL 表
- apache - 在 CentOS 7 中 SSL 连接到 Apache 服务器端口 443
- javascript - 部分匹配文件到字符串 - 字符串和 CSV 文件都包含名称中的时间戳,两个时间戳/名称之间差异的秒数
- javascript - Netlify Forms Nuxt JS 错误 - POST https://festive-fermi-f2a8f1.netlify.app/ 404。未捕获(承诺)错误:请求失败,状态码 404
- api - 我在使用 Youtube RATE API 时遇到问题
- django - Django 迁移修改继承的默认值
- http - 无法读取整个响应正文