user113454
user113454

Reputation: 2373

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

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)

Upvotes: 7

Views: 8492

Answers (2)

Tudor
Tudor

Reputation: 62439

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 {
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500185

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...

Upvotes: 15

Related Questions