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()
.