Using static with this

suggest change

Static gives a method or variable storage that is not allocated for each instance of the class. Rather, the static variable is shared among all class members. Incidentally, trying to treat the static variable like a member of the class instance will result in a warning:

public class Apple {
    public static int test;
    public int test2;
}

Apple a = new Apple();
a.test = 1; // Warning
Apple.test = 1; // OK
Apple.test2 = 1; // Illegal: test2 is not static
a.test2 = 1; // OK

Methods that are declared static behave in much the same way, but with an additional restriction:

You can’t use the this keyword in them!
public class Pineapple {

    private static int numberOfSpikes;   
    private int age;

    public static getNumberOfSpikes() {
        return this.numberOfSpikes; // This doesn't compile
    }
public static getNumberOfSpikes() {
    return numberOfSpikes; // This compiles
}

}

In general, it’s best to declare generic methods that apply to different instances of a class (such as clone methods) static, while keeping methods like equals() as non-static. The main method of a Java program is always static, which means that the keyword this cannot be used inside main().

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


static keyword:
* Using static with this

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
64 static keyword
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap