繼承和多態性 -- 方法和變量的覆蓋和隱藏


隱藏: 子類在繼承父類的時候,會隱藏父類的變量(不管是靜態變量還是實例變量)和父類的static靜態方法。此時,子類不能訪問父類的方法和變量,但是如果將子類強制轉換爲父類,則可以訪問父類隱藏的變量(不管是靜態變量還是實例變量)和static靜態方法。

覆蓋:子類中繼承父類的時候,會覆蓋父類的實例方法。此時,子類不能訪問父類的方法和變量,但是如果將子類強制轉換爲父類,還是不能訪問父類被覆蓋的實例方法。這個是實現多態性的關鍵。


實例變量:是指被聲明在類而不是方法裏面的,實例變量存在於所屬的對象中。

class Inherit_Parent{
	int x = 1 ;
	static int y = 2;
	int z = 3;
	public Inherit_Parent() {
		super();
	}
	
	public void func(){
		
		System.out.println("父類func(x)方法 -- x = "+ x + " y = "+ y + " z="+z);	
	}
	
	public static void func_static(){
		
		System.out.println("父類func_static(x)方法: ");	
	}
	
}

public class Inherit_Child extends Inherit_Parent {

	int x = 4 ;
	static int y = 5;
	int z = 6;
	
	public Inherit_Child() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public void func(){
		
		System.out.println("子類func(x)方法 -- x = "+ x + " y = "+ y + " z="+z);	
	}
	
	public static void func_static(){
		
		System.out.println("子類func_static(x)方法: ");	
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Inherit_Child child1 = new Inherit_Child();
		System.out.println("child1: x = "+child1. x + " y = "+child1. y + " z="+ child1.z);	
		child1.func();
		child1.func_static();
		
		Inherit_Parent parent2 =(Inherit_Parent) child1;
		System.out.println("parent2: x = "+parent2. x + " y = "+parent2. y + " z="+ parent2.z);	
		parent2.func();
		parent2.func_static();
	}

}


打印出來的log爲:

child1: x = 4 y = 5 z=6
子類func(x)方法 -- x = 4 y = 5 z=6
子類func_static(x)方法: 
parent2: x = 1 y = 2 z=3
子類func(x)方法 -- x = 4 y = 5 z=6
父類func_static(x)方法: 


通過log可以看出,強制將子類child1向上轉型爲父類parent2,

通過parent2讀取的實例變量,仍然是父類的x/y/z(即log:parent2: x = 1 y = 2 z=3)

通過parent2讀取的實例方法func(),卻是被覆蓋了的子類的方法(即log:子類func(x)方法 -- x = 4 y = 5 z=6)。如果要執行父類的方法,那麼調用super.func()。

通過parent2讀取的靜態static方法func_static(),仍然是父類的方法(即log:父類func_static(x)方法: )





發佈了56 篇原創文章 · 獲贊 17 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章