[Java][資策會][Lab-5]繼承練習

題目:產生一個名為Elephant的Class延伸至Animal Class

此類別有一個成員變數為name

有一個覆寫成員方法speak,用以列印父類別的兩個成員變數和自己的成員變數

最後再main()中分別透過建構子產生兩個Animal

  1. Animal年紀3歲體重8.0公斤
  2. 另一個為Elephant年紀、體重、名字為8歲,1200.0公斤,大象

思考進程:

  1. 產生Elephant  class 繼承Animal
  2. 寫出建構式並繼承Animal的建構式
  3. 覆寫方法speak()
  4. new出新物件並使用方法

Animal.java

public class Animal{

      int age = 0; 
  	   float weight = 0;	
  
     
		void speak() {
    		System.out.println("age: " + age);
    		System.out.println("weight:" + weight);
		}
		Animal( int age, float weight){
		    this.age=age;
		    this.weight=weight;
		}

  } 

Elephant.java

public class Elephant extends Animal{
	
	String name="";
	
	Elephant( int age, float weight ,String name){
		super(age,weight);
		this.name=name;
	}
	
	void speak() {
    	System.out.println("age: " + age);
    	System.out.println("weight:" + weight);
    	System.out.println("name:" + name);    	
	} 
}

AnimalTest.java

public class AnimalTest {
    public static void main (String args[]) {
			Animal animal1 = new Animal(3 , 8.0f);
			Elephant elephant = new Elephant(8,1200.0f,"大象"); 
			animal1.speak();     
            elephant.speak();  
    }
}