简体   繁体   中英

When a class implements two interfaces, interfaces have same method name but different return type why it wont work?

When a class implements two interfaces, interfaces have same method name but different return type why it wont work? java will give compiler error for this,Why cant we overload the methods in the interface_1 class?

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;
        }
    }

The reason you cannot do that is the same why you cannot overload a method on its return type alone: Java lacks a syntax to choose which method you would like to call when method names and parameters are identical.

When you write

object res = obj.add();

the compiler has no idea which of the two add methods you would like to call, the one returning an int or the String , because their names and parameters are the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM