Java使用static与this
示例
静态给出未分配给类的每个实例的方法或变量存储。相反,静态变量在所有类成员之间共享。顺便说一句,尝试将静态变量视为类实例的成员将导致警告:
public class Apple {
public static int test;
public int test2;
}
Apple a = new Apple();
a.test = 1; //警告
Apple.test = 1; //好
Apple.test2 = 1; //非法:test2不是静态的
a.test2 = 1; //好声明为静态的方法的行为几乎相同,但有一个额外的限制:
您不能this在其中使用关键字!
public class Pineapple {
private static int numberOfSpikes;
private int age;
public static getNumberOfSpikes() {
return this.numberOfSpikes; //这不编译
}
public static getNumberOfSpikes() {
return numberOfSpikes; //这样编译
}
}通常,最好声明适用于类的不同实例的泛型方法(例如克隆方法)static,同时保持类似equals()非静态的方法。的mainJava程序的方法始终是静态的,这意味着该关键字this不能使用内main()。