我們可以在 Java 中從靜態方法呼叫超類的函式嗎?
繼承可以定義為一個(父/超)類獲取另一個(子/從)類的屬性(方法和欄位)的過程。透過使用繼承,可以按層次結構對資訊進行管理。繼承屬性的類稱為子類,而其屬性被繼承的類稱為超類。簡而言之,在繼承中,可以使用子類的物件訪問超類的成員(變數和方法)。
示例
class SuperClass {
public void display(){
System.out.println("Hello this is the method of the superclass");
}
}
public class SubClass extends SuperClass {
public void greet(){
System.out.println("Hello this is the method of the subclass");
}
public static void main(String args[]){
SubClass obj = new SubClass();
obj.display();
obj.greet();
}
}輸出
Hello this is the method of the superclass Hello this is the method of the subclass
從靜態上下文中呼叫超類方法
是的,您可以從子類的靜態方法呼叫超類的方法(使用子類的物件或超類的物件)。
示例
class SuperClass{
public void display() {
System.out.println("This is a static method of the superclass");
}
}
public class SubClass extends SuperClass{
public static void main(String args[]){
//Calling methods of the superclass
new SuperClass().display(); //superclass constructor
new SubClass().display(); //subclass constructor
}
}輸出
This is a static method of the superclass This is a static method of the superclass
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP