static 关键字
1.静态变量或方法不属于对象,依赖类
2.静态变量是全局变量,生命周期从类被加载后一直到程序结束
3.静态变量只有存一份,在静态方法中存储
4.静态变量是本类所有对象共享一份
5.建议不要使用对象名去调用静态数据,直接使用类名去调用
7.静态方法不能访问非静态属性合方法,只能访问静态。(不能使用this。this表示当前对象的意思,对象不是静态)
8.用类名调用的东西一定是静态的
9.static修饰一个方法,那么这个方法属于类,不属于对象的,直接用类名调用
/**
static 关键字
1.静态变量或方法不属于对象,依赖类
2.静态变量是全局变量,生命周期从类被加载后一直到程序结束
3.静态变量只有存一份,在静态方法中存储
4.静态变量是本类所有对象共享一份
5.建议不要使用对象名去调用静态数据,直接使用类名去调用
7.静态方法不能访问非静态属性合方法,只能访问静态。(不能使用this。this表示当前对象的意思,对象不是静态)
8.用类名调用的东西一定是静态的
9.static修饰一个方法,那么这个方法属于类,不属于对象的,直接用类名调用
*/
public class keyword {
public static void main(String[] args){
/**
Role beibei=new Role("刘备"+"蜀国"); //这是第一部分 注释是为了得出下面static静态变量(全局变量)的用法
Role yunchang=new Role("关羽"+"蜀国");
Role feifei=new Role("张飞"+"蜀国");
*/
Role beibei=new Role("刘备");
Role yunchang=new Role("关羽");
Role feifei=new Role("张飞");
System.out.println(beibei.Info());
System.out.println(yunchang.Info());
System.out.println(feifei.Info());
System.out.println(beibei.country);
System.out.println(beibei.country);
System.out.println(beibei.country);
System.out.println("---------------------------------");
beibei.country="秦国";
System.out.println(beibei.country);
System.out.println(beibei.country);
System.out.println(beibei.country);
System.out.println("--------------------------------");
System.out.println(Role.country);//用类名调用静态变量一定是静态的
}
}
class Role{
private String name;
//private static String country="蜀国"; /**静态变量(全局变量)*/
/**
* 静态方法区:存储静态变量,类信息(方法) 如 country="蜀国";
*/
static String country="蜀国";
public Role(String name,String country){ //第一部分
this.name=name; //运行是自动忽略
this.country=country;
}
public Role(String name){
this.name=name;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
// 静态方法不能访问非静态属性合方法,只能访问静态。
public static void setCountry(String country){
Role.country=country;
}
/** public void setCountry(String country){
this.country=country;
}
public String getCountry(){
return country;
}*/
public String Info(){
return "name"+name+",country:"+country;
}
}