1.static 修饰符应用范围
static修饰符只能用来修饰类中定义的成员变量、成员方法、代码块以及内部类(内部类有专门章节进行讲解)。
2.static 修饰成员变量
static 修饰的成员变量称之为类变量。属于该类所有成员共享。
示例
package cn.lyxq.test04;
public class ChinesePeople {
private String name;
private int age;
public static String country = "中国";
public ChinesePeople(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package cn.lyxq.test04;
public class ChinesePeopleTest {
public static void main(String[] args) {
ChinesePeople cp1 = new ChinesePeople("张三",20);
System.out.println(ChinesePeople.country);
ChinesePeople.country="日本";
ChinesePeople cp2 = new ChinesePeople("李四",30);
System.out.println(ChinesePeople.country);
ChinesePeople cp3 = new ChinesePeople("王五",32);
System.out.println(ChinesePeople.country);
}
}
如果类变量是公开的,那么可以使用 类名.变量名 直接访问该类变量
3.static 修饰成员方法
static 修饰的成员方法称之为类方法,属于该类所有成员共享。
package cn.lyxq.test04;
public class ChinesePeople {
private String name;
private int age;
private static String country = "中国";
public ChinesePeople(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//类方法
public static String getCountry() {
return country;
}
//类方法
public static void setCountry(String country) {
ChinesePeople.country = country;
}
}
package cn.lyxq.test04;
public class ChinesePeopleTest {
public static void main(String[] args) {
ChinesePeople cp1 = new ChinesePeople("张三",20);
ChinesePeople.setCountry("日本");
ChinesePeople cp2 = new ChinesePeople("李四",30);
System.out.println(ChinesePeople.getCountry());
ChinesePeople cp3 = new ChinesePeople("王五",32);
System.out.println(cp3.getCountry());//不是最优访问方式
}
}
如果类方法是公开的,那么可以使用 类名.方法名直接访问该类方法。
4.static 修饰代码块
static 修饰的代码块被称为静态代码块,在JVM第一次记载该类时执行。因此,静态代码代码块只能执行一次,通常用于一些系统设置场景。
package cn.lyxq.test04;
public class ChinesePeople {
private String name;
private int age;
//使用static修饰的成员变量称为类变量,不会随着成员变化而变化,属于所有成员共享
private static String country ;
//static修饰的代码块称为静态代码块,在JVM第一次加载该类的时候执行,只能执行一次
static{
country = "中国";
System.out.println("country属性已经被赋值");
}
public ChinesePeople(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//类方法
public static String getCountry() {
return country;
}
//类方法
public static void setCountry(String country) {
ChinesePeople.country = country;
}
}
package cn.lyxq.test04.test;
import cn.lyxq.test04.ChinesePeople;
public class ChinesePeopleTest {
public static void main(String[] args) {
ChinesePeople cp = new ChinesePeople("张三",20);
}
}