(this.static variable) vs (static variable)

abcson :

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.

Joachim Sauer :

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!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144715&siteId=1