“this”对象与非静态对象

时间:2015-04-16 15:27:48

标签: java static this instance

考虑一下:

public class Test {

    public static int numberOfInstances = 0;
    public int myInstanceID;
    public String myInstanceName;

静态变量不需要在实例中调用,它可以在任何地方使用:

Test.numberOfInstances

创建实例时,我只在构造函数中执行此操作:

public Test(int id, String name) {
    myInstanceID = id;
    myInstanceName = name;
    numberOfInstances += 1;
}

我最近发现了this关键字,并注意到了它的一些用途:

public Test() {
    this(numberOfInstances + 1, "newInstance");
    numberOfInstances += 1;
}

根据我的注意,this关键字允许您调用另一个类'构造函数。它还允许您这样做:

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

对于java,我非常不同意这种风格;相同的变量名称,我没有看到使用this的重点,特别是在查看docs示例之后。我看看这个:

public Test(int a, int b) {
    x = a;
    y = b;

但是,不需要使用this关键字;在我的代码中,我的班级中有一个变量(例如xCoordinate),我不使用this关键字(它不是静态的)。

我一直在努力理解的是非静态变量和this变量之间的区别。有区别吗?在我的一个班级(乒乓球拍),我有这个:

public class Pong {
    public int xCoordinate;
    public int yCoordinate;

依旧...... 我从不在任何地方使用this关键字,数据存储在自己的实例中。

最重要的是,我的问题是非静态变量和this.变量之间的区别是什么。这是标准的编码实践吗?为什么我会在非静态变量上使用this关键字?

5 个答案:

答案 0 :(得分:1)

如果通常情况下,构造函数的参数变量名称(比如x)与类的字段相同,那么字段名称将被传递的参数遮蔽。

在这种情况下,使用

this来消除歧义:this.x表示字段x。这很有道理。 this表示"引用当前实例"。

因此,像this.x = x;这样的陈述很常见。

如果您仍然不喜欢Java样式,并且对类字段采用m_x - 样式表示法,那么您可以在构造函数中编写m_x = x;。正如您正确指出的那样,this不是必需的。

正如您所指出的,

this也用作委托构造函数的表示法。

答案 1 :(得分:1)

" this" keyword允许您区分方法变量和实例变量:

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

    public void add(int x, int y) {
        this.x += x;
        this.y += y;
    }
}

答案 2 :(得分:1)

我想你几乎已经回答了自己的问题。你提供了这个功能

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

但是,如果你用这种方式写它会怎么想?

public Test(int x, int y) {
    x = x;
    y = y;
}

注意到我删除了第二个函数中的this。因此,xy只是指本地xy变量。 this允许您指定您确实要使用非静态类变量xy

答案 3 :(得分:1)

没有this个变量。它只是用来告诉编译器你要更改的变量是声明的字段而不是局部变量,以防它们具有相同的名称。

对于构造函数部分,这只是具有多个构造函数的类的快捷方式。您可以编写一次代码,然后从替代构造函数中调用它。

还有一个类似的关键字super,它允许您调用超类的方法和构造函数:

public SomeClass(int x) {
    super(x);
    super.someMethod(); // even if we would have overridden someMethod(),
                        // this will call the one from the superclass
}

答案 4 :(得分:0)

以下是您需要'this'关键字的一个实例:

public class Pong {
    public int xCoordinate;
    public int yCoordinate;

    public Pong (int xCoordinate, int yCoordinate) {
        this.xCoordinate = xCoordinate;
        this.yCoordinate = yCoordinate;
    }
}