Using static with this
suggest changeThe static keyword gives a field storage that is not allocated for each instance of the class, and marks a method as belonging to the class rather than to an instance. A static variable is shared among all instances of the class. Incidentally, referring to a static variable through an instance may 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 int getNumberOfSpikes() {
return this.numberOfSpikes; // This doesn't compile
}
}
public static int getNumberOfSpikes() {
return numberOfSpikes; // This compiles
}
In general, it’s best to declare methods that do not use instance state 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().
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents