關(guān)于Java繼承的一些復(fù)習(xí)
以下,作者講述了在復(fù)習(xí)Java繼承時的一些心得??匆欢魏唵蔚拇a
- public class Test {
- public static void main(String[] args){
- B b=new B(0);
- int y=b.getY();
- }
- }
- class A {
- public static int x=2; //1.
- private int y=2; //2.
- protected int z; //5.
- A(){ //3.
- x=x+1;
- showX(); //4.
- }
- public void showX(){
- System.out.println("A.x="+x);
- }
- public int getY(){
- return y;
- }
- }
- class B extends A {
- B(int x){
- x=x+2; //只對局部x操作
- showX();
- }
- public void showX(){
- System.out.println("B.x="+x);
- }
- public int getY(){ //6.
- System.out.println("B.y="+(super.getY()+x));
- return super.getY()+x;
- }
- }
- //輸出
- //B.x=3 //動態(tài)綁定
- //B.x=3
- //B.y=5
1. public static int x被繼承到B,成為B的私有域。
2. B中仍然有一個名為y的域,但是無法直接訪問,需要通過super.getY()
3. 如果子類構(gòu)造函數(shù)沒有顯式調(diào)用超類構(gòu)造函數(shù),將會自動調(diào)用超類的無參構(gòu)造函 數(shù),若超類沒有無參構(gòu)造函數(shù),子類中又沒有顯式調(diào)用,則編譯器報錯
4. java默認(rèn)動態(tài)綁定機制,若不需要動態(tài)綁定則將方法定義為final阻止繼承
5. 類A的protected修飾符的數(shù)據(jù)或方法,可以被同個包中的任何一個類訪問(包括子類),也可以被不同包中的A的子類訪問。
6. 覆蓋一個方法時,子類的方法可見性不能低于父類方法的可見性。
以上就是有關(guān)Java繼承的幾點心得,出自51CTO的 “就像以往” 博客。
【編輯推薦】