简体   繁体   中英

Return types and multiple inheritance?

interface i1{
    int test();
}

interface i2{
    String test();
}

class Test implements i1,i2{
    <Return type> test(){
         //code here
    }
}

If return type of implemented method is int , error says Return type is incompatible with i2.test() If return type of implemented method is String , error says Return type is incompatible with i1.test()

How should I implement those two interfaces in my class Test

Any Help appreciable.

You can't. They're incompatible. Only the method name and arguments are considered in this case.

Your choices are:

  1. Change the name of one of the methods
  2. Make the argument lists different contain different types

How should I implement those two interfaces in my class Test

Either implement them in two different classes, or rename (or change the parameter signature) one of the interface methods.

It is not possible to solve this by only filling in some appropriate return type.

You'll have to find an alternative solution; for example rename the test method in one of the interfaces.

This will never works you must have to find an alternative.ie Rename the methods or u can provide the inner class implementation as following

class Test {


 static i1 i=new i1() {

    @Override
    public int test() {

        return 0;
    }
};

        static i2 i22=new i2() {

    @Override
    public String test() {

        return "String";
    }
};


public static void main(String...strings ){

    if(someObject instanceof String){

        i.test();



    } else {

        i22.test();
    }



}



}

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