作用:
修饰属性,则声明为static的变量实质上是全局变量(生命周期直到程序结束)。
修饰方法:那么该方法与对象无关,或者说是共享,可直接用类名调用。
修饰类:可修饰内部类。
静态方法不能访问非静态属性和方法,因为静态方法先加载。
案例:
代码:
package no1;
public class test7 {
public static void main(String[] args) {
Role beibei = new Role("刘备","蜀国");
Role yunchang = new Role("云长","蜀国");
Role feifei = new Role("张飞","蜀国");
System.out.println(beibei.getInfo());
System.out.println(yunchang.getInfo());
System.out.println(feifei.getInfo());
}
}
class Role{
private String name;
private String country;
public Role() {
}
public Role(String name, String country) {
this.name = name;
this.country = country;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCountry() {
return country;
}
public String getInfo() {
return "name="+name+",country="+country;
}
}
运行结果:
分析:
修改代码:
package no1;
public class test7 {
public static void main(String[] args) {
// Role beibei = new Role("刘备","蜀国");
// Role yunchang = new Role("云长","蜀国");
// Role feifei = new Role("张飞","蜀国");
Role beibei = new Role("刘备");
Role yunchang = new Role("云长");
Role feifei = new Role("张飞");
System.out.println(beibei.getInfo());
System.out.println(yunchang.getInfo());
System.out.println(feifei.getInfo());
}
}
class Role{
private String name;
private static String country = "蜀国"; //静态变量,全局变量
public Role() {
}
public Role(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCountry() {
return country;
}
public String getInfo() {
return "name="+name+",country="+country;
}
}
运行结果:
name=刘备,country=蜀国
name=云长,country=蜀国
name=张飞,country=蜀国
分析:
静态变量或方法依赖于类。
静态变量是全局变量,生命周期从类加载后一直都程序结束。
静态变量只存一份,在静态方法区中存储。