我正在学习 Java,并正在阅读文档。
this page 上有一行我无法理解 -
... Also, class methods cannot use the this keyword as there is no instance for this to refer to. ...
我以为只有静态类方法不能使用this
关键字。
为了测试这一点,我编写了以下代码,它可以编译。
import java.math.*;
class Point {
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double getDistanceFromOrigin() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
}
我有一个类,其中一个方法引用了this
。
我是否以某种方式误解了事情?
最佳答案
类方法是静态方法。 “类方法”是一种绑定(bind)到类定义的方法(使用 static
关键字),与您编写的对象/实例方法相反,您可以在构建的对象上调用它们基于那个类。
您编写的代码有两个对象/实例方法,没有类方法。如果你想要 Java 中的类方法,你可以将其设为静态,然后你就不能使用 this
。
关于java - 类中的this关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17218949/