Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic interface with a method that return a list

I have a Generic interface (Pack<A extends PackAnimal>) with one method that returns List<A>. Today I've found that if in a class that implements the interface I forget to speficy the class (class XXX implements PackAnimal) the return type is not checked in compilation time and fail during execution

interface PackAnimal {
}
class Buffalo implements PackAnimal {
}

interface LonelyAnimal {
}
class Puma implements LonelyAnimal {
}

interface Pack<A extends PackAnimal> {
    List<A> getMembers();
}

class PumaPack implements Pack {

    @Override
    public List<Puma> getMembers() {
        return null;
    }
}

Why is that? How could I force that if there any type of mistake in the declaration the compilation will fail?

like image 765
Narkha Avatar asked Jun 14 '26 09:06

Narkha


1 Answers

Your List is declared with an unknown type. Use the class type:

interface Pack<A extends PackAnimal> {
    List<A> getMembers();
}

// won't compile because Puma not within bound
class PumaPack implements Pack<Puma> {
    List<Puma> getMembers() {return null;}
}

// compiles OK
class BuffaloPack implements Pack<Buffalo> {
    List<Buffalo> getMembers() {return null;}
}

But you can't stop someone coding a raw (missing type) implementation like your PumpPack example, however you will get a compiler warning:

// compile warning
class PumaPack implements Pack {
    List getMembers() {return null;}
}

If you set your compile to fail if there are warnings:

javac -Werror ...

then you will achieve your goal even for raw types.

like image 193
Bohemian Avatar answered Jun 17 '26 01:06

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!