jash.liao的JAVA整理教學:JAVA件導向-建構子(constructor)
jash.liao的JAVA整理教學:JAVA件導向–建構子(constructor)
線上執行:http://www.tutorialspoint.com/compile_java_online.php / http://www.compilejava.net/
code2html:http://tohtml.com/
// our main class becomes a file but the main method is still found
publicclass HelloWorld {
publicstaticvoid main(String[] args) { Animal puppy1 =new Animal(6,70); puppy1.speak();
Animal puppy2 =new Animal(142); puppy2.speak();
Animal puppy3 =new Animal(); puppy3.speak(); } }
class Animal { privateint age; privateint weight;
public Animal(int a,int w){ setAge(a); setWeight(w); System.out.println("2 parameters of the constructor,Animal's object created...."); }
public Animal(int w){ setAge(3); setWeight(w); System.out.println("1 parameter of the constructor,Animal's object created...."); } public Animal(){ 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; } }
publicvoid speak(){ System.out.println("Hello,I am "+ getAge()+" years old. I weighed "+ getWeight()+" kg"); } }
|