Java 中的介面可以過載方法嗎?
多型是指物件根據上下文執行不同操作(或表現出不同行為)的能力。
過載是實現多型的一種機制,其中一個類包含兩個名稱相同但引數不同的方法。
每當你呼叫此方法時,方法體將根據引數與方法呼叫繫結。
示例
在下面的 Java 程式中,Calculator 類有兩個名為 addition 的方法,唯一的區別是其中一個包含 3 個引數,另一個包含 2 個引數。
在這裡,我們可以透過傳遞兩個整數或三個整數來呼叫 addition 方法。根據我們傳遞的整數數量,將執行相應的方法。
public class Calculator {
public int addition(int a , int b){
int result = a+b;
return result;
}
public int addition(int a , int b, int c){
int result = a+b+c;
return result;
}
public static void main(String args[]){
Calculator cal = new Calculator();
System.out.println(cal.addition(12, 13, 15));
}
}輸出
40
介面中過載方法
是的,您可以在介面中擁有過載方法(名稱相同但引數不同的方法)。您可以實現此介面並透過其方法實現方法過載。
示例
import java.util.Scanner;
interface MyInterface{
public void display();
public void display(String name, int age);
}
public class OverloadingInterfaces implements MyInterface{
String name;
int age;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void display(String name, int age) {
System.out.println("Name: "+name);
System.out.println("Age: "+age);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your age: ");
int age = sc.nextInt();
OverloadingInterfaces obj = new OverloadingInterfaces();
obj.display();
obj.display(name, age);
}
}輸出
Enter your name: Krishna Enter your age: 25 This is the implementation of the display method Name: Krishna Age: 25
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP