Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
user810430 Avatar asked May 07 '12 08:05

user810430


People also ask

Can anonymous inner class extend?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.

Can anonymous class extend abstract class?

You create an anonymous class that extends your abstract class. In the snipped below, you are extending AbstractDemo and provide implementations for its abstract methods. Show activity on this post. New class was defined (without a name, so called anonymous class)

What is the purpose of anonymous class in Java?

An anonymous class must implement all the abstract methods in the super class or the interface. An anonymous class always uses the default constructor from the super class to create an instance.

Which is true about an anonymous inner class in Java?

D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.


1 Answers

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() {    ... 
like image 93
NPE Avatar answered Sep 26 '22 18:09

NPE