繼承(Inheritance)
在上述程式碼中,class B 繼承自 class A。這表示 B 繼承了 A 的所有公有和受保護(protected)的成員變數和方法。具體來說,B 可以訪問和使用 A 中定義的公有方法 m1() 和 m2(),以及繼承了 A 中的私有變數 a1,儘管 B 不能直接訪問或修改 a1。
覆寫(Overriding)
覆寫是指子類別提供了對繼承自父類別的方法的具體實現。這樣,即使使用子類別的物件呼叫父類別的方法,實際上執行的也是子類別的實現。
在此例中,class B 覆寫了從 class A 繼承的 m2() 方法:
java
複製程式碼
class B extends A {
// Other fields and methods
public void m2() {
b1 = 1;
b2 = 2;
}
}
當 B 類的物件呼叫 m2() 方法時,將會執行 B 類中定義的 m2() 方法,而不是 A 類中的 m2() 方法。
class B 的物件內含的資料欄位(data fields)
class B 的物件會包含從 A 繼承的成員變數和 B 自己定義的成員變數。具體來說:
從 A 繼承的資料欄位:
private int a1(雖然 a1 是私有的,但它仍然是 B 類物件的一部分,不能直接被 B 訪問。)
B 自己定義的資料欄位:
private int b1
private int b2
綜合上述,class B 的物件內含的資料欄位如下:
java
複製程式碼
class B extends A {
private int a1; // Inherited from class A (not directly accessible)
private int b1; // Defined in class B
private int b2; // Defined in class B
}
完整程式碼
讓我們整合所有資訊,並改正一些語法錯誤,展示完整的物件導向程式碼:
java
複製程式碼
class A {
private int a1;
public void m1() {
a1 = 1;
}
public void m2() {
a1 = 3;
}
// Getter for a1 to allow class B to access it if needed
protected int getA1() {
return a1;
}
// Setter for a1 to allow class B to modify it if needed
protected void setA1(int a1) {
this.a1 = a1;
}
}
class B extends A {
private int b1;
private int b2;
@Override
public void m2() {
b1 = 1;
b2 = 2;
}
public void m3() {
// Use setter to modify a1 since a1 is private in class A
setA1(2);
}
}
在這段程式碼中,B 類繼承了 A 類的所有成員,並且覆寫了 A 類的 m2() 方法。此外,B 類還新增了一個 m3() 方法,用於修改 a1 的值,通過使用 A 類的 setA1 方法來間接訪問和修改私有成員 a1。