Java 中父類的靜態方法為何會被子類隱藏?
當我們有兩個類,其中一個類繼承另一個類,並且如果這兩個類具有相同的方法(包括引數和返回型別,例如,sample),則子類中的方法會覆蓋父類中的方法。
即,由於它是繼承。如果我們例項化子類,則會在子類物件中建立父類成員的副本,因此子類物件可以使用這兩個方法。
但是,如果呼叫方法(sample),則會執行子類中的 sample 方法,從而覆蓋父類的方法。
示例
class Super{
public static void sample(){
System.out.println("Method of the superclass");
}
}
public class OverridingExample extends Super {
public static void sample(){
System.out.println("Method of the subclass");
}
public static void main(String args[]){
Super obj1 = (Super) new OverridingExample();
OverridingExample obj2 = new OverridingExample();
obj1.sample();
obj2.sample();
}
}輸出
Method of the superclass Method of the subclass
覆蓋靜態方法
當父類和子類包含相同的方法(包括引數),並且它們都是靜態方法時。父類中的方法將被子類中的方法隱藏。
這種機制簡稱為方法隱藏,儘管父類和子類具有相同簽名的方法,但如果它們是靜態的,則不被視為覆蓋。
示例
class Super{
public static void demo() {
System.out.println("This is the main method of the superclass");
}
}
class Sub extends Super{
public static void demo() {
System.out.println("This is the main method of the subclass");
}
}
public class MethodHiding{
public static void main(String args[]) {
MethodHiding obj = new MethodHiding();
Sub.demo();
}
}輸出
This is the main method of the subclass
方法隱藏的原因
方法過載的關鍵在於,如果父類和子類具有相同簽名的方法,則子類物件可以使用這兩個方法。根據你用於儲存物件的 物件型別(引用),將執行相應的方法。
SuperClass obj1 = (Super) new SubClass(); obj1.demo() // invokes the demo method of the super class SubClass obj2 = new SubClass (); obj2.demo() //invokes the demo method of the sub class
但是,對於靜態方法,由於它們不屬於任何例項,因此需要使用類名訪問它們。
SuperClass.demo(); SubClass.Demo();
因此,如果父類和子類具有相同簽名的靜態方法,儘管子類物件可以使用父類方法的副本,但由於它們是靜態的,因此方法呼叫在編譯時本身就會解決,靜態方法無法被覆蓋。
但是,由於靜態方法的副本可用,如果你呼叫子類方法,則父類的方法將被重新定義/隱藏。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP