Can an anonymous class be declared as implementing an interface and extending a class

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

Yes, in Java, an anonymous class can be declared as implementing an interface and extending a class simultaneously. This allows you to create a class on the fly that provides a specific implementation for an interface while also inheriting from a class.

Here is an example:

java
interface MyInterface {
void interfaceMethod();
}

class MyBaseClass {
void baseClassMethod() {
System.out.println("Base class method");
}
}

public class Main {
public static void main(String[] args) {
// Anonymous class implementing an interface and extending a class
MyInterface myObject = new MyBaseClass() {
@Override
public void interfaceMethod() {
System.out.println("Implementation of interfaceMethod");
}
};

myObject.interfaceMethod();
// You can also call methods from the base class
((MyBaseClass) myObject).baseClassMethod();
}
}

In this example, an anonymous class is created that implements the MyInterface interface and extends the MyBaseClass class. The interfaceMethod is implemented in the anonymous class, and you can also call methods from the base class using type casting.