靜態(tài)變量:類變量,為此類所有對(duì)象共享
靜態(tài)方法:靜態(tài)方法里沒有this引用
不能在靜態(tài)方法中訪問非靜態(tài)的成員變量和方法
可以直接通過類訪問靜態(tài)成員,即使不存在該類的對(duì)象
//Student.java
package cn.edu.uibe.oop;
public class Student {
String name; //學(xué)生姓名
static int counter=0; //學(xué)生對(duì)象的數(shù)目
public Student(String name){
this.name = name;
counter++; //對(duì)象計(jì)數(shù)加1,需要用靜態(tài)變量才能為所有對(duì)象共享
}
public void print(){
System.out.println("name="+name+"\tcounter="+counter);
}
public static void showCounter(){
System.out.println("counter="+counter);
//System.out.println(name); //error,靜態(tài)方法里面不能訪問非靜態(tài)的成員變量和方法
//this. //error,靜態(tài)方法里面沒有this引用
}
public static void main(String[] args) {
Student[] student = {
new Student("zhangsan"),
new Student("lisi"),
new Student("zhaowu")
};
for(int i=0;i
student[i].print();
}
new Student("wuming");
System.out.println("counter="+Student.counter);
Student.showCounter();
}
}