(二) 一:static修饰成员变量。
静态修饰符static关键字修饰成员变量。
首先,我们看一段代码:
class Hero{
//成员变量
String name;
String country;
//构造方法
public Hero(String name,String country){
this.name=name;
this.country=country;
}
//成员方法
public void show(){
System.out.println("姓名是:"+name+",王国是:"+country);
}
}
//测试类
class HeroTest{
public static void main(String[] args){
//创建Hero对象
Hero timo = new Hero("提莫","约德尔王国");
timo.show();
Hero naer = new Hero("纳尔","约德尔王国");
naer.show();
}
}
编译执行后输出结果:
然后我们对上述代码做一个小小的改变,用static关键字来修饰Hero类中的country成员变量,并且这个时候我们增加一个新的为一个参数构造方法,我们再写测试类用新的构造方法进行测试:
class Hero{
//成员变量
String name;
static String country; //用static修饰country!!!
//构造方法
//只有name参数
public Hero(String name){
this.name=name;
}
//name和country两个参数
public Hero(String name,String country){
this.name=name;
this.country=country;
}
//成员方法
public void show(){
System.out.println("姓名是:"+name+",王国是:"+country);
}
}
//测试类
class HeroTest{
public static void main(String[] args){
//创建Hero对象
//使用两个参数的构造方法
Hero timo = new Hero("提莫","约德尔王国");
timo.show();
//使用一个参数的构造方法
Hero naer = new Hero("纳尔");
naer.show();
}
}
我们再看看运行结果:
这时,我们发现,我们并没有给对象 naer 给定country的值,但是执行结果中也出现了他的country属性。所以,首先我们就可以知道static关键字可以修饰成员变量,用static修饰的成员变量可以被共享使用。
对于上述Hero类,还可以这样写:在Hero类中直接对country进行赋值,后面创建对象时就可以都不用去考虑country属性,可以直接去使用,并且默认值都是"约德尔王国"。大家可以自己编写测试类进行测试。
class Hero{
//成员变量
String name;
static String country="约德尔王国"; //用static修饰country并赋值!!!
//构造方法
//只有name参数
public Hero(String name){
this.name=name;
}
}