0

For example:

Runnable r = new Runnable() {
    @Override
    public void run() {

    }
};

Why there is no error? Interfaces cannot be instantiated.

user13630431
  • 23
  • 1
  • 6

3 Answers3

1

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 FOOvsimplements FOO`, it's the same concept.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

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();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface [Runnable].
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
flaxel
  • 4,173
  • 4
  • 17
  • 30