Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีสืบทอด (Implements) หลาย Interface ใน Java


Interface ใน Java คล้ายกับคลาส แต่ประกอบด้วยเมธอด abstract และฟิลด์ที่เป็น final และ static เท่านั้น

เช่นเดียวกับคลาส คุณสามารถขยาย (extends) interface หนึ่งจากอีก interface ได้ โดยใช้คีย์เวิร์ด extends สามารถสืบทอดหลาย interface พร้อมกันได้ โดยคั่นด้วยเครื่องหมายจุลภาค (,)

interface MyInterface extends ArithmeticCalculations, MathCalculations {

ตัวอย่างโปรแกรมแสดงการสืบทอดหลาย Interface

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 + " คือ: " + 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 คือ: 2.0
4^3 = 64.0

หมายเหตุ: ตัวอย่างโค้ดข้างต้นขาดการ import java.util.Scanner ซึ่งควรเพิ่มไว้ด้านบนของไฟล์