一個小例子對多態簡單的理解

來源:互聯網
上載者:User

標籤:blog   java   問題   div   ar   new   log   不同的   

class Parent{    int age;String name;public Parent(String name, int age){    this.name = name;    this.age = age;}    public void writeWay(){    System.out.println("毛筆!"); }  }  class Child extends Parent{    int age;String name;//這裡只說為了說明一個問題,其實完全可以有父類繼承而來。public Child(String name, int age){    super("張某某", age+25);    this.name = name;this.age = age;}public void writeWay(){    System.out.println("鋼筆!"); }  }public class PC{   public static void main(String[] args){        Parent p = new Child("張三", 25);        System.out.println(p.name + " " + p.age);//表現出父親的屬性p.writeWay();//調用的是自身的方法   }}/*一個叫做張三的人,偽裝(比如貼上鬍子,看上去像自己父親的年齡;然後對外稱自己為張某某)成了自己的父親張某某,既然是偽裝,當然要表現出父親所具有的屬性啦! 但是如果讓這個張三去寫幾行字,張三和父親都有屬於自己的寫字方式,要知道每個人的寫字方式肯定是不同的。所以張三這個人就會用自己的寫字方式去寫字!*/

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.