static:静态
有多少人就要改多少次
静态的内容在内存中保留一份,并且各个对象之间可以进行共享
使用p1.country=“民国”会产生误导,故不推荐这样访问静态变量
腿甲使用类名访问静态变量 Person.country = “民国”
public class Person {
String name;
static String country = "大清"; //加了static,是共享的
String address;
public Person(String name,String address) {
this.name=name;
this.address=address;
}
public static void main(String[] args) {
Person p1 = new Person("赵铁柱","八大胡同");
Person p2 = new Person("李小花","朝阳门");
// 大清亡了
Person.country="民国"; //推荐使用类名去访问静态变量
System.out.println(p1.country);
System.out.println(p2.country);
}
}
特点
- 数据共享
- 属于类,不属于对象
- 优先于对象产生
二 通用构造器 静态构造器
创建对象过程:
- 静态构造器
- 通过用构造器
- 构造方法 -> 创建对象
注意:
由于创建对象的过程是在静态内容加载完成之后,在静态方法和静态块里都不能使用this
public class Test {
String name;
public static void chi() {
//System.out.println(this.name); 在static里不允许使用this
}
public static void pen() {
System.out.println("hhh");
}
public static void main(String[] args) {
pen(); //在静态方法里调用静态的东西是可以的
Test.pen(); //使用类名访问静态方法
}
}
总结:
静态内容优先于对象产生,且不属于对象,
静态内容一般使用类名访问