jash.liao的JAVA整理教學:JAVA件導向- static 成員
jash.liao的JAVA整理教學:JAVA件導向– static 成員
線上執行:http://www.tutorialspoint.com/compile_java_online.php / http://www.compilejava.net/
code2html:http://tohtml.com/
成員 (member) 宣告時若使用關鍵字 static 修飾,該成員變成屬於類別 (class) 而非物件 (object) ,因此使用 static 就不需要先建立物件
class Animal { privateint age; privateint weight;
privatestaticint number =0;
public Animal(int a,int w){ number++; setAge(a); setWeight(w); System.out.println("2 parameters of the constructor,Animal's object created...."); }
public Animal(int w){ number++; setAge(3); setWeight(w); System.out.println("1 parameter of the constructor,Animal's object created...."); } public Animal(){ number++; setAge(3); setWeight(15); System.out.println("Animal's object created...."); }
publicint getAge(){ return age; } publicvoid setAge(int n){ if(n <0){ age =1; } else{ age = n; } }
publicint getWeight(){ return weight; }
publicvoid setWeight(int n){ if(n <0){ weight =1; } else{ weight = n; } }
publicstaticint getNumber(){ return number; }
publicvoid speak(){ System.out.println("Hello,I am "+ getAge()+" years old. I weighed "+ getWeight()+" kg"); } }
publicclass HelloWorld{ publicstaticvoid main(String[]args){ System.out.println("Hello World"); System.out.println("There is "+ Animal.getNumber()+" of Animal.");
Animal puppy1 =new Animal(6,70); puppy1.speak();
Animal puppy2 =new Animal(142); puppy2.speak();
Animal puppy3 =new Animal(); puppy3.speak();
System.out.println("There are "+ Animal.getNumber()+" of Animal."); } }
|