如何用 Java 繼承多個介面?
Java 中的介面類似於類,但它僅包含抽象方法和 final 和 static 的欄位。
就像類一樣,您可以使用 extends 關鍵字從另一個介面擴充套件一個介面。您還可以使用 extends 關鍵字從一個介面擴充套件多個介面,使用逗號 (,) 分隔介面,如下所示 -
interface MyInterface extends ArithmeticCalculations, MathCalculations{示例
以下是 Java 程式,演示如何從單個介面擴充套件多個介面。
interface ArithmeticCalculations{
public abstract int addition(int a, int b);
public abstract int subtraction(int a, int b);
}
interface MathCalculations {
public abstract double squareRoot(int a);
public abstract double powerOf(int a, int b);
}
interface MyInterface extends MathCalculations, ArithmeticCalculations {
public void displayResults();
}
public class ExtendingInterfaceExample implements MyInterface {
public int addition(int a, int b) {
return a+b;
}
public int subtraction(int a, int b) {
return a-b;
}
public double squareRoot(int a) {
return Math.sqrt(a);
}
public double powerOf(int a, int b) {
return Math.pow(a, b);
}
public void displayResults(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
ExtendingInterfaceExample obj = new ExtendingInterfaceExample();
System.out.println("Result of addition: "+obj.addition(a, b));
System.out.println("Result of subtraction: "+obj.subtraction(a, b));
System.out.println("Square root of "+a+" is: "+obj.squareRoot(a));
System.out.println(a+"^"+b+" value is: "+obj.powerOf(a, b));
}
public static void main(String args[]){
new ExtendingInterfaceExample().displayResults();
}
}輸出
Enter the value of a: 4 Enter the value of b: 3 Result of addition: 7 Result of subtraction: 1 Square root of 4 is: 2.0 4^3 value is: 64.0
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP