繼承,多態的再學習
繼承
本人,小菜一枚。一直在學習java,對於java中繼承,多態一直以來不太瞭解。對繼承多態,一直處於一種半知半解的狀態,今天又特意看了一下,決定寫下這篇文章。
從字面意思理解就是兒子繼承了他爸的東西,這樣兒子就有了他爸的東西。
再深入一點理解,就是兒子對於繼承的他爸的東西不太滿意,畢竟是老一代的嘛 東西過時了對吧,需要與時俱進,就稍加改進改進。OK,代碼實現一下
//父類
public class Father{
public void hello(){
System.out.println("this is 老子");
}
}
//子類
public class Son extends Father {
public void hello(){
System.out.println("this is 小子");
}
}
//測試類
public class Test {
public static void main(String[] args) {
Father father = new Son();
Son son = new Son();
father.hello();
son.hello();
}
}
看一下運行結果:
this is 小子
this is 小子
這兒子太不孝順了,竟然不讓調用他老子的。今個非教訓他一頓,來個強制轉換,
public class Test {
public static void main(String[] args) {
Father father = new Son();
Son son = new Son();
father.hello();
son.hello();
//強制轉換
Father f = (Father)father;
f.hello();
}
}
再來看一下運行結果:
this is 小子
this is 小子
this is 小子
這……,或許是他老子的確實跟不上時代了。
總結
上例中,我們實例化了兩個Son對象,分別以Father和Son類型來引用它。father.hello()表面上是調用了father類型的方法,但是它實際上是一個虛擬方法。以Father類型引用的變量father調用say方法時,實際上並不是調用Father類中的hello方法,而是Son類中的hello方法。該行爲被稱爲虛擬方法調用。 –這段話引用自(作爲一枚小菜,表達能力還有待提高):
如果子類中沒有重寫父類中的方法,那麼我們也可以使用father.hello()來調用父類中的hello方法,還可以用father來調用父類中未被重寫的方法。
多態
多態是同一個行爲具有多個不同表現形式或形態的能力。就比如跑這個動作,如果是人的話就是用兩條腿跑,如果是貓的話就是四條腿。那跑這個動作就具有多態性。OK,代碼實現一下
public interface Run {
void run();
}
//人
public class Human implements Run {
public void run() {
System.out.println("人類,兩條腿跑");
}
}
//貓
public class Cat implements Run {
public void run() {
System.out.println("貓,四條腿跑");
}
}
//測試類
public class Test {
public static void main(String[] args) {
Run cat = new Cat();
Run human = new Human();
cat.run();
human.run();
}
}
運行結果如下:
貓,四條腿跑
人類,兩條腿跑
上面的測試類中,使用的是Run類的引用,但卻是實例化的Cat,Human類的對象,所以就調用了對應的對象的方法。剛纔,在Run接口中寫了一個default方法(JDK8中允許在接口中實現方法,但是要用default修飾),用cat也可以調用。
多態不僅可以通過接口來體現,還可以通過繼承來體現,多個子類對同一方法的重寫可以表現出不同的行爲。也是多態的體現。
突然想起來了轉型,既然子類對象的引用可以調用父類的方法,爲什麼還要轉型呢?那就寫到這吧,繼續學習去…….
最後: 由於這是本菜的第一篇文章,難免有用詞不當的地方,而且作爲一名小菜,有些術語用的可能不正確。如果有錯誤的地方還請各位大神不吝賜教。