Multiple inheritance for an anonymous class
Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object
.
For example:
Runnable r = new Runnable() {
public void run() { ... }
};
Here, r
is an object of an anonymous class which implements Runnable
.
An anonymous class can extend another class using the same syntax:
SomeClass x = new SomeClass() {
...
};
What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.
An anonymous class usually implements an interface:
new Runnable() { // implements Runnable!
public void run() {}
}
JFrame.addWindowListener( new WindowAdapter() { // extends class
} );
If you mean whether you can implement 2 or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:
public class MyClass {
private interface MyInterface extends Runnable, WindowListener {
}
Runnable r = new MyInterface() {
// your anonymous class which implements 2 interaces
}
}
I guess nobody understood the question. I guess what this guy wanted was something like this:
return new (class implements MyInterface {
@Override
public void myInterfaceMethod() { /*do something*/ }
});
because this would allow things like multiple interface implementations:
return new (class implements MyInterface, AnotherInterface {
@Override
public void myInterfaceMethod() { /*do something*/ }
@Override
public void anotherInterfaceMethod() { /*do something*/ }
});
this would be really nice indeed; but that's not allowed in Java.
What you can do is use local classes inside method blocks:
public AnotherInterface createAnotherInterface() {
class LocalClass implements MyInterface, AnotherInterface {
@Override
public void myInterfaceMethod() { /*do something*/ }
@Override
public void anotherInterfaceMethod() { /*do something*/ }
}
return new LocalClass();
}