简体   繁体   中英

Extends and Interface has same method with the same parameters but different return types

In java I have to create a class that extends another class and implements an interface. This is the class I have to extend

public class Cell  {

    public void receiveRat(RatInterface pRat) {     
    
    } 
}

This is the interface that I have to implement

public interface HoleInterface {    
    public int[] receiveRat(RatInterface pRat);
}

I have made the class

public class Hole extends Cell  implements HoleInterface {

    public Hole() {
    
    }

    @Override
    public int[] receiveRat(RatInterface pRat) {
        // TODO Auto-generated method stub
        return null;    
    }

The int[] in the hole class doesn't work because Hole extends the Cell and Cell has a method like that with the return type void. What am I suppose to do?

As far as I know, that is not possible. The return types clash. What you could do, is either rename one of the methods to something like public void getRat(RatInterface pRat){...} or let Cell implement HoleInterface, removing the public void receiveRat(RatInterface pRat) {...} method and replacing it with the @Override public int[] receiveRat(RatInterface pRat) {...} method. If then Hole extends Cell, it indirectly also implements HoleInterface. Like this:

public class Cell implements HoleInterface {
    @Override
    public int[] receiveRat(RatInterface pRat) {
        return null;
    }
//Now indirectly implements HoleInterface through Cell
public class Hole extends Cell{
    public Hole() {
    
    }
    @Override
    public int[] receiveRat(RatInterface pRat) {
        return null;    
    }

But thats just an idea... How to fix your problem depends on the specific task or problem you want to solve.

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