For example:
Runnable r = new Runnable() {
@Override
public void run() {
}
};
Why there is no error? Interfaces cannot be instantiated.
For example:
Runnable r = new Runnable() {
@Override
public void run() {
}
};
Why there is no error? Interfaces cannot be instantiated.
That syntax isn't for instantiating things. Or at least, not just for that.
That syntax is sugar (short hand) for:
class Whatever$DontLookAtThisName implements Runnable {
@Override public void run() {
}
}
Runnable r = new Whatever$DontLookAtThisName();
Had you used a class there, it'd have been shortfor for class Whatever$DontLookAtThis extends TheThingieYouPutThere
, but other than 'extends FOOvs
implements FOO`, it's the same concept.
You are creating an anonymous class that implements the Runnable
interface. Note: That since this interface has a Single Abstract Method, in Java 8+ you could just do
Runnable r = () -> System.out.println("run");
r.run();
There is a nice documentation from Oracle about this topic:
... an anonymous class is an expression. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
The anonymous class expression consists of the following:
new
operator