Java extends用法詳解
概要:
理解繼承是理解面向對象程序設計的關鍵。在Java中,通過關鍵字extends繼承一個已有的類,被繼承的類稱為父類(超類,基類),新的類稱為子類(派生類)。在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執行得:
Animal breathe! Animal breathe!
java文件中的每個類都會在文件夾bin下生成一個對應的.class文件。執行結果說明派生類繼承了父類的所有方法。
(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(); } }
執行結果: Animal breathe Fish breathe
在子類中定義一個與父類同名,返回類型,參數類型均相同的一個方法,稱為方法的覆蓋。方法的覆蓋發生在子類與父類之間。另外,可用super提供對父類的訪問。