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?
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.
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)
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.
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.
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() { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With