类中的this关键字

时间:2013-06-20 16:31:07

标签: java class oop this

我正在学习Java,并阅读文档。

this page上有一行我无法理解 -

  

...   此外,类方法不能使用this关键字,因为没有要引用的实例。   ...

我认为只有静态类方法无法使用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

我是否以某种方式误解了事情?

5 个答案:

答案 0 :(得分:5)

类方法静态方法。 “类方法”是绑定到类定义的方法(使用static关键字),而不是您编写的对象/实例方法,以便您可以在基于该方法构建的对象上调用它们类。

您编写的代码有两个对象/实例方法,没有类方法。如果您想在Java中使用类方法,则将其设置为静态,然后不能使用this

答案 1 :(得分:1)

  

我认为只有static类方法无法使用this关键字。

你是对的。类中的static方法属于类,而不属于对象引用。因此,要证明您的句子,只需添加static方法并在其中使用this关键字。例如:

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);
    }

    public static double getDistanceBetweenPoints(Point point1, Point point2) {
        //uncomment and it won't compile
        //double result = this.x;
        //fancy implementation...
        return 0;
    }

}

答案 2 :(得分:1)

您是对的,只有static类方法无法使用this关键字,但您的代码示例是非静态的,因此this完全有效。

答案 3 :(得分:1)

您在实例方法中使用this,该方法将引用当前实例。

public double getDistanceFromOrigin() {
    return Math.sqrt(this.x*this.x + this.y*this.y);
}

如果将方法更改为静态方法,则this将不可用,因为静态方法与类绑定而不是与类的特定实例绑定,而this指的是当前如果在方法中使用,则为类的实例。

public static double getDistanceFromOrigin() {
    return Math.sqrt(this.x*this.x + this.y*this.y); // compilation error here
}

答案 4 :(得分:1)

在您发布的链接上阅读内容后,似乎使用了措辞Class methods来引用静态方法


  

课程方法

     

Java编程语言也支持静态方法   静态变量。静态方法,其中包含静态修饰符   他们的声明应该用类名调用,而不是   需要创建类的实例,如

您不能在静态方法中使用this,因为没有要引用的实例(无this)。

相关问题