【Java基础】关键字:static
1.static说明
我们希望某些数据在内存空间中只有一份,比如Chinese类,每个对象都共享countryName这个变量,而不用在每个实例变量中单独放一个countryName的变量。那么就可以用static修饰,表示静态的。
(1)使用static可以修饰属性、方法、代码块、内部类
(2)相当于这些结构属于该类,可以直接通过类名.静态属性
、类名.静态方法
调用(权限允许),随着类的加载而加载。
(3)优先于对象的创建,修饰的成员被所有对象所共享。
2.static使用
(1)static修饰属性
Chinese类
public class Chinese {
String name;
Integer age;
static String countryName;
}
执行如下语句
public static void main(String[] args) {
Chinese.countryName = "中国";
Chinese c1 = new Chinese();
c1.name = "张三";
c1.age = 18;
Chinese c2 = new Chinese();
c2.name = "李四";
c2.age = 30;
c1.countryName = "CHN";
c2.countryName = "CHINA";
System.out.println(Chinese.countryName);//CHINA
}
JVM内存解析,static修饰的结构存放在方法区中,countryName初始默认值为null,c1和c2对象修改的是同一个变量
(2)static修饰方法
① static方法内部只能访问static修饰的属性或方法。
② static方法中不能有this,也不能有super;this和super指一个对象,而static成员优先于对象创建,使用this或super相当于空的对象指针,因此编译不通过。
③ static修饰的方法不能被重写;重写是为了实现多态,子类重写父类static方法,执行的是父类中的static方法,达不到多态目的。
Father son = new Son();
son.staticMethod();
public class Person {
private int id;
private static int total = 0;
public static int getTotalPerson(){
id++; //报错,static方法中不能调用非static结构
return total;
}
public static void setTotalPerson(int total){
this.total = total; //报错,static方法中不能有this或super
}
public Person(){
total++;
id = total;
}
}
可以直接通过Person.getTotalPerson()
调用方法,不用创建对象。