Anonymous extending a class and implementing an interface at the same time?

こ雲淡風輕ζ 提交于 2019-12-08 19:25:37

问题


Suppose I have an interface called Interface, and a concrete class called Base, which, to make thing a bit more complicated, has a ctor that requires some arguments.

I'd like to create an anonymous class that would extend Base and implement Interface.

Something like

 Interface get()
 {
     return new Base (1, "one") implements Interace() {};
 }

That looks reasonable to me, but it doesn't work!

(P.S: Actually, the Interface and Base are also generic classes :D. But I'll ignore that for now)


回答1:


This scenario makes little sense to me. Here's why: assume class Base is this:

class Base {
    public void foo();
}

and Interface is this:

interface Interface {
    public void bar();
}

Now you want to create an anonymous class that would be like this:

class MyClass extends Base implements Interface {
}

this would mean that MyClass inherits (or possibly overrides) method bar from Base and must implement method foo from Interface. So far so good, your class has these two methods either way.

Now, think what happens when you are returning an object of type Interface from your method: you only get the functionality that Interface offers, namely method foo. bar is lost (inaccessible). This brings us down to two cases:

  1. Extending Base is useless because you do not get to use its methods, since the new object is seen as an Interface.
  2. Interface also has a method foo, but that would mean that Base itself should implement Interface, so you can just extend Base directly:
class Base implements Interface {
    public void foo();
    public void bar();
}

class MyClass extends Base {
}



回答2:


No, you can't do that with an anonymous class. You can create a named class within a method if you really want to though:

class Base {
}

interface Interface {
}

public class Test {
    public static void main(String[] args) {
        class Foo extends Base implements Interface {
        };

        Foo x = new Foo();
    }
}

Personally I'd usually pull this out into a static nested class myself, but it's your choice...



来源:https://stackoverflow.com/questions/9514366/anonymous-extending-a-class-and-implementing-an-interface-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!