Java多態(一)

來源:互聯網
上載者:User

標籤:

父類:public class Parent {    public String name;    private String pass;        public void say1(AA aa){                System.out.println("parent say1");    }    @SuppressWarnings("unused")    private void eat(){        System.out.println("parent eat");    }    public String getPass() {        return pass;    }    public void setPass(String pass) {        this.pass = pass;    }}子類:public class Child extends Parent{        public static void main(String[] args) {        AA a = new AA();                /**         * 向上轉型:程式運行調用某一方法時,先查看Parent類是否有調用的方法,         * 若有則就去調用子類中的方法,若父類沒有此方法,則編譯錯誤。         *          */        Parent p = new Child();        p.say1(a);                /**         * 向下轉型,編譯和運行皆不會出錯,這裡的向下轉型是安全的。         */        Child child = (Child) p;        child.say1(a);        child.say2(a);                /**         * 向下轉型,編譯無錯,運行時報錯: java.lang.ClassCastException         * 不安全的向下轉型。         */        //Parent p2 = new Parent();        //Child c2 = (Child) p2;        //c2.say1(a);    }        public void say1(AA aa){                System.out.println("Child say1");    }        public void say2(AA aa){                System.out.println("Child say2");    }}class AA {    public void sys() {        System.out.println("A is");     }}class BB extends AA{    public void sys() {        System.out.println("B is");     }}

 

Java多態(一)

聯繫我們

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