classHuman{staticint total =0;String name;int age;int height;Human(Stringstr){ name = str; total++;}// end of constructor(String)voidprintName(){System.out.println("姓名:"+name);}// end of printName();staticvoidprintTotal(){System.out.println("總人數:"+total);}// end of printTotal();}// end of class Human
class Test{
public static void main(String[] args){
Human.printTotal();
Human tina = new Human("小婷");
tina.printName();
Human yubin = new Human("小木");
yubin.printName();
Human.printTotal();
}// end of main(String[])
}// end of class Test
總人數:0
姓名:小婷
姓名:小木
總人數:2
類別名稱 . 靜態方法 ;
void printName(){
// 除了存取一般變數name,還多了存取靜態變數total
System.out.println("姓名:"+name+",總人數:"+total);
}// end of printName()
總人數:0
姓名:小婷,總人數:1
姓名:小木,總人數:2
總人數:2
static void printName(){
System.out.println("姓名:"+name);
}// end of printName();
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field name
at Test$Human.printName
at Test.main