1、前期綁定 後期綁定
當子類向上轉型爲基類對象的時候,不知道原來是哪一個子對象,所以需要辨別,此時用到了綁定,來判定哪一個子對象。
前期綁定:運行程序之前就綁定。
後期綁定:Java中除了static方法和final方法(private方法屬於final方法)之外,其他所有方法都屬於後期綁定。
2、靜態方法的子父類的覆寫
3、靜態變量與非靜態變量 在和 main方法調用順序問題
class Cha{
private String s;
Cha(String s){
this.s = s;
System.out.println("Cha s="+s);
}
}
class Des{
private String s;
Des(String s){
this.s = s;
System.out.println("Des s="+s);
}
}
class Living{
private Cha c = new Cha("is living");
private Des d = new Des("basic living");
Living(){System.out.println("Living");}
}
class Animal extends Living{
private Cha c = new Cha("is Animal");
private Des d = new Des("basic Animal");
Animal(){System.out.println("Animal");}
}
class Amphibian extends Animal{
private Cha c = new Cha("is Amphibian");
private Des d = new Des("basic Amphibian");
Amphibian(){System.out.println("Amphibian");}
}
public class Frog extends Amphibian{
private Cha c = new Cha("is Frog");
private Des d = new Des("basic Frog");
Frog(){System.out.println("Frog con");}
public static void main(String[] args) {
Frog f = new Frog();
}
}
//out
Cha s=is living
Des s=basic living
Living
Cha s=is Animal
Des s=basic Animal
Animal
Cha s=is Amphibian
Des s=basic Amphibian
Amphibian
Cha s=is Frog
Des s=basic Frog
Frog con
執行順序:靜態成員變量(父或子) -> mian方法裏面new本類 -> 非靜態成員變量(父類)-> 構造方法(父類) -> 非靜態成員變量(子類)-> 構造方法(子類)。
4、父類構造函數中使用了被子類覆寫的方法,會調用子類覆寫的方法。若未在構造函數中調用覆寫方法,則會使用父類方法。
不可利用向上轉型調用子類新添加的方法,因爲父類沒有該方法。
class Glypn{
void draw(){System.out.println("Glypn");}
Glypn(){
System.out.println("Glypn ..");
draw();//正常情況下不會在構造函數中調用覆寫方法
System.out.println("Glypn ...");
}
}
class Round extends Glypn{
private int r = 1;
Round(int r){
this.r = r;
System.out.println("Round .."+r);
}
void draw(){System.out.println("Round draw " +r);}
}
public class Poly {
public static void main(String[] args) {
new Round(2);
}
}
//out
Glypn ..
Round draw 0
Glypn ...
Round ..2
5、繼承和實現接口
若繼承類A中和實現接口B有一模一樣的方法,則子類C可以不用寫該方法,但若不相同時,必須實現接口方法,且不能以有無返回值來判斷方法是否相同,只能根據參數列表判斷。