[英]Class implements two interfaces with the same method but different checked exceptions
[英]When a class implements two interfaces, interfaces have same method name but different return type why it wont work?
當一個類實現兩個接口時,接口具有相同的方法名稱,但返回類型不同,為什么它不起作用? Java將為此給出編譯器錯誤,為什么我們不能重載interface_1類中的方法?
import static java.lang.System.out;
interface A1{
int add();
}
interface A2{
String add();
}
public class interface_1 implements A1,A2{
public static void main(String args[]){
out.println("a");
}
@Override
public String add() {
// TODO Auto-generated method stub
return null;
}
@Override
public int add() {
// TODO Auto-generated method stub
return 2;
}
}
無法執行此操作的原因與無法單獨在其返回類型上重載方法的原因相同:Java缺少一種語法,當方法名稱和參數相同時,該語法無法選擇要調用的方法。
當你寫
object res = obj.add();
編譯器不知道您要調用的兩個add
方法中的哪一個,它們返回一個int
或String
,因為它們的名稱和參數相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.