Java中如何继承多个接口?
Java中的接口类似于类,但它仅包含最终和静态的抽象方法和字段。
就像类一样,您可以使用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("输入a的值: "); int a = sc.nextInt(); System.out.println("输入b的值: "); int b = sc.nextInt(); ExtendingInterfaceExample obj = new ExtendingInterfaceExample(); System.out.println("添加结果: "+obj.addition(a, b)); System.out.println("减法结果: "+obj.subtraction(a, b)); System.out.println("的平方根 "+a+" is: "+obj.squareRoot(a)); System.out.println(a+"^"+b+" 价值是: "+obj.powerOf(a, b)); } public static void main(String args[]){ new ExtendingInterfaceExample().displayResults(); } }输出结果
输入a的值: 4 输入b的值: 3 添加结果: 7 减法结果: 1 的平方根 4 is: 2.0 4^3 价值是: 64.0