題目:產生一個Animal calss,裡面有兩個成員變數
- age (int)
- weight (float)
創建一個成員方法名叫speak()列印出age和weight的值
透過建構子產生一個Animal年紀和體重分別為兩歲和五公斤,並列印此Animal成員變數的值
思考進程:
- 創建Animal Class創建變數age和weight
- 創建方法speak列印出變數age和weight
- 創建建構子並宣告argument age和weight
- 創建另一個AnimalTest Class
- new出一個animal1 argument為age=2,weight=5.
- 重要:建構子不能有回傳值,有回傳值等於另一個方法
Animal Class
public class Animal{
int age = 0;
float weight = 0;
public void speak() {
System.out.println("age: " + age);
System.out.println("weight:" + weight);
}
public Animal(int age,float weight){
this.age=age;
this.weight=weight;
}
}
AnimalTest Class
public class AnimalTest {
public static void main (String args[]) {
Animal animal1 = new Animal(2 , 5);
animal1.speak();
}
}