jash.liao的JAVA整理教學:JAVA件導向-建構子(constructor)

jash.liao的JAVA整理教學:JAVA件導向-建構子(constructor)

jash.liao的JAVA整理教學:JAVA件導向建構子(constructor)

 

線上執行:http://www.tutorialspoint.com/compile_java_online.php / http://www.compilejava.net/

code2htmlhttp://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");
    }
}

 

 

 


發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *