Java 中靜態方法的隱藏
當超類和子類包含相同的例項方法(包括引數)時,呼叫時,子類的方法會覆蓋超類的方法。
示例
class Super{ public void sample(){ System.out.println("Method of the Super class"); } } public class MethodOverriding extends Super { public void sample(){ System.out.println("Method of the Sub class"); } public static void main(String args[]){ MethodOverriding obj = new MethodOverriding(); obj.sample(); } }
輸出
Method of the Sub class
方法隱藏
當超類和子類包含相同的方法(包括引數)並且它們是靜態的時,超類中的方法將被子類中的方法隱藏。這種機制稱為方法隱藏。
示例
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();
因此,如果超類和子類具有相同簽名的靜態方法,儘管超類方法的副本可用於子類物件。由於它們是靜態的,因此方法呼叫在編譯時本身就會解析,靜態方法無法被重寫。
但是,由於靜態方法的副本可用,如果您呼叫子類方法,則超類的方法將被重新定義/隱藏。
廣告