package day04;
/*
static 静态
修饰成员变量:
修饰方法:
*/
public class Demo09 {
public static void main(String[] args) {
Voter voter1 = new Voter();
voter1.name = "张三";//没有static修饰,用实例.变量调用
voter1.vote();//投票
System.out.println("当前票数:"+Voter.count);//static修饰后,用类名.变量调用
Voter voter2 = new Voter();
voter2.name = "李四";
voter2.vote();
System.out.println("当前票数:"+Voter.count);
Voter voter3 = new Voter();
voter3.name = "王五";
voter3.vote();//非静态的方法调用,实例.方法名
Voter.getCount();//静态方法的调用,类名.方法名
for(int i=0;i<20;i++){
Voter v = new Voter();
v.name = "选民"+i;
v.vote();
Voter.getCount();
}
}
}
/*
选民类
*/
class Voter{
String name;//选民的名字,每个实例特有的属性
static int count;//所有选民共用的,属于类的
//投票方法
public void vote(){
if(count == 20){
System.out.println("投票活动结束。");
}else{
System.out.println(name+"感谢投票!");
count++;
}
}
//静态方法
public static void getCount(){
//非静态的成员变量,在静态方法中不能使用
System.out.println(/*name+*/"当前票数:"+count);
}
//类同名时,将包名带上
day01.Demo01 d = new day01.Demo01();
day02.Demo01 d1 = new day02.Demo01();
}
|