java中的繼承

來源:互聯網
上載者:User

java中採用關鍵字extends繼承一個類

子類可以使用父類中的方法(除了private方法之外)子類可以覆蓋(override)父類中的方法(private因為invisible不能覆蓋,final也不能覆蓋)可以將子類對象賦值給自身或者直系長輩(即父類,父類的父類。。),而不能反過來將父類對象賦值給子類。當將子類對象賦值給父類變數的時候,不可以使用子類專有的方法。父類
public class Father {/** * @param args */void method1(){System.out.println("F.method1");}void method2(){System.out.println("F.method2");}private void method4()  //invisible in 子類{System.out.println("F.method4");}final void method5()  //can not override{System.out.println("F.method5");}}

子類

public class Son extends Father{void method2(){System.out.println("S.method2");}void method3(){System.out.println("S.method3");}}

測試

public class Test {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubFather tf = new Father();System.out.println("Father tf = new Father(),tf.m1,tf.m2");tf.method1();tf.method2();Father tf2 = new Son();System.out.println("Father tf2 = new Son(),tf2.m1,tf2.m2");tf2.method1();tf2.method2();//使用了子類方法,不能使用父類中沒有,子類中定義的方法Son ts = new Son();  //cannot convert from Father to SonSystem.out.println("Son ts = new Son(),ts3.m1,ts3.m2");ts.method1();ts.method2();ts.method3();}

聯繫我們

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