Java 教程

Java控制語句

面向物件程式設計

Java內建類

Java檔案處理

Java錯誤和異常

Java多執行緒

Java同步

Java網路程式設計

Java集合

Java介面

Java資料結構

Java集合演算法

高階Java

Java雜項

Java APIs和框架

Java類引用

Java有用資源

Java - extends關鍵字



Java 的extends關鍵字用於繼承類的屬性。以下是extends關鍵字的語法。

語法

class Super {
   .....
   .....
}
class Sub extends Super {
   .....
   .....
}

示例程式碼

以下是一個演示Java繼承的示例。在這個例子中,您可以看到兩個類,名為Calculation和My_Calculation。

使用extends關鍵字,My_Calculation繼承了Calculation類的addition()和Subtraction()方法。

複製並貼上以下程式到名為My_Calculation.java的檔案中

示例

class Calculation {
   int z;
	
   public void addition(int x, int y) {
      z = x + y;
      System.out.println("The sum of the given numbers:"+z);
   }
	
   public void Subtraction(int x, int y) {
      z = x - y;
      System.out.println("The difference between the given numbers:"+z);
   }
}

public class My_Calculation extends Calculation {
   public void multiplication(int x, int y) {
      z = x * y;
      System.out.println("The product of the given numbers:"+z);
   }
	
   public static void main(String args[]) {
      int a = 20, b = 10;
      My_Calculation demo = new My_Calculation();
      demo.addition(a, b);
      demo.Subtraction(a, b);
      demo.multiplication(a, b);
   }
}

輸出

編譯並執行上述程式碼,如下所示。

javac My_Calculation.java
java My_Calculation

程式執行後,將產生以下結果:

The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

在給定的程式中,當建立My_Calculation類的物件時,超類的內容副本將被建立在其內。這就是為什麼,使用子類的物件,您可以訪問超類的成員。

Inheritance

超類引用變數可以持有子類物件,但是使用該變數只能訪問超類的成員,因此為了訪問兩個類的成員,建議始終為子類建立引用變數。

如果您考慮上述程式,您可以如下所示例項化類。但是使用超類引用變數(本例中為cal)您無法呼叫屬於子類My_Calculation的方法multiplication()

Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

以下示例展示了相同的概念。

示例

class Calculation {
   int z;
	
   public void addition(int x, int y) {
      z = x + y;
      System.out.println("The sum of the given numbers:"+z);
   }
	
   public void Subtraction(int x, int y) {
      z = x - y;
      System.out.println("The difference between the given numbers:"+z);
   }
}

public class My_Calculation extends Calculation {
   public void multiplication(int x, int y) {
      z = x * y;
      System.out.println("The product of the given numbers:"+z);
   }
	
   public static void main(String args[]) {
      int a = 20, b = 10;
      Calculation demo = new My_Calculation();
      demo.addition(a, b);
      demo.Subtraction(a, b);
   }
}

輸出

編譯並執行上述程式碼,如下所示。

javac My_Calculation.java
java My_Calculation

程式執行後,將產生以下結果:

The sum of the given numbers:30
The difference between the given numbers:10

注意 - 子類繼承其超類的所有成員(欄位、方法和巢狀類)。構造器不是成員,因此不會被子類繼承,但是可以從子類呼叫超類的構造器。

java_basic_syntax.htm
廣告