[Java][資策會][Lab-6]多型練習

題目:產生一個名叫PolyAnimal的class

程式跟LAB5相同,連結:https://dotblogs.com.tw/jerryhuang0306/2016/01/26/183751

在main()中透過多型來製作

思考進程:

  1. 產生PolyAnimal class
  2. 將物件的父類別由Elephant改成Animal

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

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();  
    }
}