Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 605
user113454 Avatar asked Mar 01 '12 10:03

user113454


People also ask

Can you extend a class and implement an interface at the same time?

Note: A class can extend a class and can implement any number of interfaces simultaneously.

Can an anonymous class implement an interface in Java?

The syntax of anonymous classes does not allow us to make them implement multiple interfaces.

Can you extend an abstract class and implement an interface?

Abstract Classes Compared to Interfaces With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

Which of the following is true for an anonymous class?

18) Which of the following is true about the anonymous inner class? Explanation: Anonymous inner classes are the same as the local classes except that they don't have any name. The main use of it is to override methods of classes or interfaces.


1 Answers

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

like image 180
Jon Skeet Avatar answered Nov 04 '22 10:11

Jon Skeet