user810430
user810430

Reputation: 11499

In Java, can anonymous classes extend another class?

Code like:

protected Interface1 varClass1 = new Interface1() {

But I would also like that this anonymous nested class also extends the class Base, something like:

protected Interface1 varClass1 = new Interface1() extends Base {
....

Is this possible in Java?

Upvotes: 30

Views: 13382

Answers (2)

rolve
rolve

Reputation: 10218

While it is not possible to both extend a class and implement an interface, what you probably what to do can be achieved using delegation.

Just create an instance of Base in the initializer of your anonymous class and use its methods from the methods you implement from Interface1.

EDIT: My answer assumes that you only want to inherit from Base because of its implementation, not because of its interface. This is a valid assumption given that the interface of Baseis not visible after assigning the object to a Interface1 variable. Therefore, I think it's better to use delegation here instead of creating a new class.

Upvotes: 3

NPE
NPE

Reputation: 500267

An anonymous class can either implement exactly one interface or extend one class.

One workaround is to create a named class that extends Base and implements Interface1, and then use that as the base class for the anonymous class:

public abstract class Base1 extends Base implements Interface1 {}

...

protected Interface1 varClass1 = new Base1() {
   ...

Upvotes: 33

Related Questions