-1
cron.addDateAction(new DateAction(d3, new Actionable() {
        @Override
        public void execute() {
            for(int i = 0; i < 10; i++){ 
                System.out.println(i);
            }
        }
    }));

I am studying and found this code; I have never seen this way of creating an object but besides that, my question is:

Actionable is an interface, so it can't be instantiated, this means the new Actionable(){...} part creates a subclass object of the interface, but why?

wattbatt
  • 447
  • 2
  • 13
  • 4
    That is called an anonymous inner class. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html – JB Nizet Jan 04 '20 at 16:12

1 Answers1

0

This is an anonymous inner class. The new operator creates an instance of an anonymous class that implements the Actionable interface with the given block of code.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I wonder how `new` knows the difference, if I write `Actionable a= new Actionable();` it's an error, but `new Actionable()` here it's not, is it a specific characteristic of new that makes it understand that with the implementation below that object is not directly an object of the interface? – wattbatt Jan 04 '20 at 16:25