In Java, can anonymous classes extend another class?

user810430 picture user810430 · May 7, 2012 · Viewed 10.6k times · Source

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?

Answer

NPE picture NPE · May 7, 2012

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() {
   ...