(this.static variable) vs (static variable) [duplicate]

问题: This question already has an answer here: Accessing a static variable via an object reference in Java 5 answers I (think) static variables are used...

问题:

This question already has an answer here:

I (think) static variables are used when you want some attribute of a class to be shared among all of its objects.

class Person{

    private String name;
    private static int qtdone = 0;
    private static int qtdtwo = 0;

    //constructor

    public Person(){
        this.name = "Generic";
        this.qtdone ++;
        qtdtwo++;
    }

    public void print_qtd(){
        System.out.println("this.qtdone is: " + this.qtdone);
        System.out.println("qtdtwo is: " + this.qtdtwo);

    }
}

public class Main {
    public static void main(String [] args) {
        Person one = new Person();
        Person two = new Person();

        one.print_qtd();
    }
}

returns

this.qtdone is: 2
qtdtwo is: 2

Which is what I expected, since qtdone and qtdtwo are modified by both "Person one" and "Person two"

What i'm not sure is the difference between this.qtdone and qtdtwo. They ended up doing the same, but I would like to confirm if they are the same or are, in fact, doing similar (but distinct) things.


回答1:

The fact that static variables can be accessed using this is a weird quirk of the Java language. There's really no reason to intentionally do this.

Either use the unqualified name qtdone or use the class name to qualify it: Person.qtdone.

Using this.qtdone works but it looks like it accesses an instance field even when it doesn't. In fact using this syntax doesn't even check if this is in fact referencing an object:

Person notReallyAPerson = null;
notReallyAPerson.qtdone++; // this works!

回答2:

this.qtdone is equivalent to qtdone or Person.qtdone. However using this for static access is not recommended.

The only difference is, that qtdone might be shadowed by a local variable. In this case, it makes sense to qualify with the class name:

setQtDone(int qtdone) {
  Person.qtdone = qtdone;
}
  • 发表于 2019-03-02 02:04
  • 阅读 ( 165 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除