Java 多態(tài)的例子

多態(tài)就是通過繼承和動態(tài)綁定來決定程序使用哪個實現(xiàn).

一個簡單的例子。

interface Animal {
    public void eat();
}

class Whale extends SeaAnimal {
    int age = 20;

    @Override
    public void eat() {
        System.out.println("Whale is eatting a small fish");
    }

    private void swimming() {
        System.out.println("Whale is swimming");
    }

    @Override
    public int getAge() {
        return age;
    }

    public static void staticSwimming() {
        System.out.println("Static whale is swimming .");
    }

}

public class SeaAnimal implements Animal {
    int age = 10;

    private void swimming() {
        System.out.println("SeaAnimal is swimming.");

    }

    public static void staticSwimming() {
        System.out.println("Static seaAnimal is swimming.");
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        SeaAnimal animal = new Whale();
        animal.swimming();
        animal.eat();
        animal.staticSwimming();
        System.out.println("The age is " + animal.age);
        System.out.println("The age is " + animal.getAge());
    }

    @Override
    public void eat() {
        System.out.println("SeaAnimal is eatting a small fish");
    }
}

輸出結果:

SeaAnimal is swimming.
Whale is eatting a small fish
Static seaAnimal is swimming.
The age is 10
The age is 20

從例子可以看出:

  • 成員變量不具備多態(tài)
  • private 方法不具備多態(tài)
  • static方法不具備多態(tài)
  • 構造方法不具備多態(tài)
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 多態(tài)的存在有三個前提: 1.要有繼承關系2.子類要重寫父類的方法3.父類引用指向子類對象 看下面幾個例子,你就全明...
    長脖子樹閱讀 5,925評論 1 4
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內(nèi)部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,811評論 18 399
  • 對象的創(chuàng)建與銷毀 Item 1: 使用static工廠方法,而不是構造函數(shù)創(chuàng)建對象:僅僅是創(chuàng)建對象的方法,并非Fa...
    孫小磊閱讀 2,186評論 0 3
  • 1、.java源文件: 一個以”.java“為后綴的源文件:只能有一個與文件名相同的類,可以包含其他類。 2、類方...
    Hughman閱讀 1,755評論 1 9
  • 2016年,我遇到了人生中最重要的事,也最讓自己揪心的事,找工作。 “要做一個什么樣的工作呢?”思前想后,怎么...
    better6789閱讀 255評論 2 1

友情鏈接更多精彩內(nèi)容