static
static 译为 “静态”.
static 可以修饰 属性 方法 代码块 内部类
static 修饰 属性
首先,属性分为两种
静态属性 和 非静态属性(实例变量)
对于静态属性: 多个对象共享同一个静态变量。当修改静态变量时,会导致其他对象调用此静态变量时,是修改过了的。这是因为static修饰的数据放在方法区的静态域中.
对于实例变量 : 每个对象都独立的拥一套类中的非静态属性。当修改其中一个对象中的非静态属性时,不会导致其他对象中同样的属性值的修改。
-
static 随着 类的加载而加载 可以通过 类 . 静态变量 的方法调用, 也可以通过对象 . 静态变量调用
-
静态属性的出现早于对象的出现 (因为static 随着类的加载而加载, 而对象的创建晚于类的加载, 有了对象,实例变量才会被加载)
-
由于类只会加载一次,所以静态变量只会加载一次.存在方法区的静态域中.
public class StaticTest {
public static void main(String[] args) {
Chinese.nation = "wuhu"; // 类 . 静态变量 早于对象的创建
Chinese c1 = new Chinese();
c1.age = 14;
c1.nation = "China"; // 对象 . 静态变量
Chinese c2 = new Chinese();
c2.age = 18;
c2.nation = "CHN"; // 对象 . 静态变量
System.out.println(c2.nation); // CHN
Chinese.age = 14; // 报错,不知道具体指那个
}
}
class Chinese {
int age;
static String nation; // 静态变量
}
static 修饰 方法 随着类的加载而加载
-
static 生命周期比非static修饰的方法长, 所以静态方法不能调用普通方法
-
静态方法可以通过类 . 方法名 也可以通过 对象 . 方法名
非静态方法中,只能通过 对象 . 方法名注意 :
在静态的方法内,不能使用this关键字、super关键字
public class StaticTest { public static void main(String[] args) { Women.play(); // play Women.height = "170"; Women w = new Women(); w.eat(); Women.dance(); } } class Women { String name; int age; static String height; public void eat () { System.out.println("eat"); study(); play(); System.out.println(height); } public void study () { System.out.println("study"); } public static void play () { System.out.println("play"); dance(); // study (); // Non-static method 'study()' cannot be referenced from a static context } public static void dance () { System.out.println("dance"); System.out.println(height); // 可以调用static类型的height // System.out.println(age); // 不可以 } public void information () { System.out.println("name :" + name + ", height" + height); } public void info () { System.out.println(Women.height); // 省略的是Women. 而不是this. } }