(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 bubble
在子類中定義一個與父類同名,返回類型,參數類型均相同的一個方法,稱爲方法的覆蓋。方法的覆蓋發生在子類與父類之間。另外,可用super提供對父類的訪問。