开发者

java: interfaces and templates

开发者 https://www.devze.com 2022-12-21 21:28 出处:网络
This doesn\'t seem to work (compiler complains that Something\'s getFoo() method doesn\'t implement HasFoo) and I can\'t figure out why or how to fix it....

This doesn't seem to work (compiler complains that Something's getFoo() method doesn't implement HasFoo) and I can't figure out why or how to fix it....

enum FooKey { BLOB1, DONUT, ... }

interface HasFoo
{
   public Object getFoo(FooKey k);
}

class Something implements HasFoo
{
    private Map<FooKey, Object> map;

    @SuppressWarnings("unchecked")
    @Override
    <T> T get开发者_开发技巧Foo(FooKey k)
    {
        return (T)map.get(k);
    }

    /* other stuff deleted */
}

I want both an interface and I also want to be able to do stuff like

Something something = ...
Blob blob1 = something.getFoo(FooKey.BLOB1);
Donut donut = something.getFoo(FooKey.DONUT);


Doesn't this work?

interface HasFoo
{
   public <T> T getFoo(FooKey k);
}


You can't override a non-generic method with a generic one. An alternative could be:

interface HasFoo
{
    <T> T getFoo(FooKey k);
}

class Something implements HasFoo
{
    private Map<FooKey, Object> map;

    @Override
    public <T> T getFoo(FooKey k)
    {
        return (T)map.get(k);
    }

    /* other stuff deleted */
}


Compiler's error really mean that methods' signatures differ:

<T> T getFoo(FooKey k)

Object getFoo(FooKey k)

Althought Object is the ultimate ancestor compiler wants signatures to be exactly same


Your interface is specifying an Object, whereas the return type of the impl is 'anything'. You need to change the interface to return T.

BTW, you could also declare your map to be <FooKey, T>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号