CodeGym /Java Blog /Toto sisi /Java 中的超級關鍵字
John Squirrels
等級 41
San Francisco

Java 中的超級關鍵字

在 Toto sisi 群組發布
super關鍵字用於不同的情況。在開始閱讀這篇文章之前,我們鼓勵您了解 Java 中的繼承,以便更好地理解。

Java中的super關鍵字是什麼?

Super是一個關鍵字,可用於調用超類的重寫方法,以及引用超類的隱藏字段。

為什麼以及何時使用 super 關鍵字?

Java super關鍵字具有三個顯式用途。
  1. 當子類也有同名數據成員時訪問父類的數據成員。
  2. 在子類中調用父類的默認或參數化構造函數。
  3. 如果子類有重寫的方法,則在子類中調用父類的方法。
讓我們藉助示例來理解上述所有三種情況。

示例 1 - 訪問父級的數據成員

示例 1 說明瞭如何在Car類型的子類中訪問Vehicle類的屬性或數據成員。確保您運行下面的代碼片段以很好地理解。

class Vehicle {

	String name = "vehicle";
}

class Car extends Vehicle {

	String name = "car";

	public void printMyName() {

		System.out.println(name);
	}

	public void printParentName() {

		// use super keyword to access 
		// parent's data member / attribute
		System.out.println(super.name);
	}

	public static void main(String[] args) {

		Car myCar = new Car();
		System.out.print("My Car's Name: "); 
		myCar.printMyName();
		
		// printing the parent's name 
		// using the super keyword 
		System.out.print("My Parent Vehicle's Name: "); 
		myCar.printParentName();
	}
}
輸出
我的車名:car 我父母的車名:vehicle

示例 2 - 在子類中訪問父類的構造函數

顯式調用super()允許您在子類中訪問父類的默認或參數化構造函數。下面是參數化構造函數的示例。父類即Shape類的構造函數在子類即Triangle類中調用(使用super() )來設置屬性。運行下面的程序來親自測試輸出。

public class Shape {

	String name;

	public Shape(String n) {

		System.out.println("Shape() parameterized constructor called!");
		name = n;
	}
}

class Triangle extends Shape {
	
	int sides = 3;
	String color;

	public Triangle(String n, String c) {
		
		// The super keyword calls the parameterized 
		// constructor of the parent (Shape) with 
		// 'n' as a parameter 
		super(n);
		
		System.out.println("Triangle() parameterized constructor called!");
		this.color = c;
	}

	public static void main(String[] args) {

		Triangle myTriangle = new Triangle("Triangle Alpha", "Yellow");
		
		System.out.println(myTriangle.name);
		System.out.println(myTriangle.color);
	}
}
輸出
調用了 Shape() 參數化構造函數!調用了 Triangle() 參數化構造函數!三角形阿爾法黃色
快速挑戰:通過使用默認構造函數重新設計上述程序來測試您的學習情況。另外,看看super()與super(arg)有何不同。

示例 3 - 在子類中訪問父類的重寫方法

示例 3 顯示瞭如何訪問子類也定義的父類的方法。下面程序中的父類Sound定義了一個方法voice()。子類Drum也有一個同名的方法,即voice()。這意味著方法voice被子類覆蓋。運行下面的程序,了解如何在子類中使用父類的方法需要 super關鍵字。

public class Sound {

	public void voice() {
		System.out.println("Play sound!");
	}
}

class Drum extends Sound {

	public void voice() {
		System.out.println("Play drums!");
	}

	public void play() {

		// The super keyword calls the 
		// voice() method of the parent 
		super.voice();
		voice();
	}
	
	public static void main(String[] args) {

		Drum myDrum = new Drum();
		myDrum.play();
	}
}
輸出
調用了 Shape() 參數化構造函數!調用了 Triangle() 參數化構造函數!三角形阿爾法黃色

結論

到本文結束時,我們希望您能夠理解super關鍵字在 Java 中的工作原理。我們鼓勵您通過實踐學習編碼。因為實踐是學習邏輯構建的最終關鍵。無論如何,只要您遇到困難,這篇文章都會歡迎您。到那時,祝您學習愉快!
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION