java 多態2

來源:互聯網
上載者:User

標籤:繼承   name   bsp   abstract   sys   重寫   pack   static   實現   

http://www.cnblogs.com/wqq0402/p/6180685.html

 

package test05;


public class DuoTai_Test02 {
/**多個對象,一個形態
* Tiger、Lion、Snake → Animal
*、多個對象,一種形態(類型)。
* 不同對象,表現出同一種形態之後。
* 可以實現同樣的功能。
*
* 此方式,需要多個子類對應一個父類。
* 往往是採用(多個)子類繼承父類來實現。
*
* @param args
*/

public static void main(String[] args) {
Animal animal = new Cat();//抽象引用指向子類對象
animal.eat();
animal.sheep();
Animal animal2 = new Dog();
animal2.eat();
animal2.sheep();
Animal animal3 = new Snack();
animal3.eat();
animal3.sheep();

DuoTai_Test02 dt = new DuoTai_Test02();
dt.test(new Cat());
dt.test(new Dog());
dt.test(new Snack());
}

public void test(Animal animals){
animals.eat();
animals.sheep();

}
}

abstract class Animal {//抽象類別
String name;
int age;
public abstract void eat();//抽象方法
public abstract void sheep();//抽象方法

}

class Cat extends Animal {
public void eat() {//方法重寫
System.out.println("貓吃");
}
public void sheep(){
System.out.println("貓睡覺");
}
}

class Dog extends Animal {
public void eat(){//方法重寫
System.out.println("狗吃");
}
public void sheep() {
System.out.println("狗睡覺");
}
}

class Snack extends Animal {
public void eat() {//方法重寫
System.out.println("蛇吃");
}

public void sheep() { //方法重寫
System.out.println("蛇睡覺");
}
}

java 多態2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.