Java extends用法詳解
創(chuàng)新互聯(lián)是一家專注于網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)與策劃設(shè)計(jì),天鎮(zhèn)網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:天鎮(zhèn)等地區(qū)。天鎮(zhèn)做網(wǎng)站價(jià)格咨詢:18980820575
概要:
理解繼承是理解面向?qū)ο蟪绦蛟O(shè)計(jì)的關(guān)鍵。在Java中,通過關(guān)鍵字extends繼承一個(gè)已有的類,被繼承的類稱為父類(超類,基類),新的類稱為子類(派生類)。在Java中不允許多繼承。
(1)繼承
class Animal{ void eat(){ System.out.println("Animal eat"); } void sleep(){ System.out.println("Animal sleep"); } void breathe(){ System.out.println("Animal breathe"); } } class Fish extends Animal{ } public class TestNew { public static void main(String[] args) { // TODO Auto-generated method stub Animal an = new Animal(); Fish fn = new Fish(); an.breathe(); fn.breathe(); } }
在eclipse執(zhí)行得:
Animal breathe! Animal breathe!
java文件中的每個(gè)類都會(huì)在文件夾bin下生成一個(gè)對(duì)應(yīng)的.class文件。執(zhí)行結(jié)果說明派生類繼承了父類的所有方法。
(2)覆蓋
class Animal{ void eat(){ System.out.println("Animal eat"); } void sleep(){ System.out.println("Animal sleep"); } void breathe(){ System.out.println("Animal breathe"); } } class Fish extends Animal{ void breathe(){ System.out.println("Fish breathe"); } } public class TestNew { public static void main(String[] args) { // TODO Auto-generated method stub Animal an = new Animal(); Fish fn = new Fish(); an.breathe(); fn.breathe(); } }
執(zhí)行結(jié)果:
Animal breathe Fish breathe
在子類中定義一個(gè)與父類同名,返回類型,參數(shù)類型均相同的一個(gè)方法,稱為方法的覆蓋。方法的覆蓋發(fā)生在子類與父類之間。另外,可用super提供對(duì)父類的訪問。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
分享名稱:Java基礎(chǔ)之extends用法詳解及簡(jiǎn)單實(shí)例
標(biāo)題網(wǎng)址:http://muchs.cn/article34/jchepe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、ChatGPT、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站收錄、品牌網(wǎng)站建設(shè)、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)