今天就跟大家聊聊有關java中extends的意思是什么,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
extends在java中的作用是繼承的意思,在Java中,通過關鍵字extends繼承一個已有的類,被繼承的類稱為父類【超類,基類】,新的類稱為子類【派生類】,并且在Java中不允許多繼承。
繼承是理解面向對象程序設計的關鍵。在Java中,通過關鍵字extends繼承一個已有的類,被繼承的類稱為父類(超類,基類),新的類稱為子類(派生類)。在Java中不允許多繼承。
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執行得:Animal breathe!
Animal breathe!
.java文件中的每個類都會在文件夾bin下生成一個對應的.class文件。執行結果說明派生類繼承了父類的所有方法。
覆蓋
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(); } }
執行結果:
Animal breathe
Fish breathe
在子類中定義一個與父類同名,返回類型,參數類型均相同的一個方法,稱為方法的覆蓋。方法的覆蓋發生在子類與父類之間。另外,可用super提供對父類的訪問。
看完上述內容,你們對java中extends的意思是什么有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。