0

I have found a this example with the following piece of code:

CompletableFuture<T> completable = new CompletableFuture<T>() {  
    @Override  
    public boolean cancel(boolean mayInterruptIfRunning) {  
        // propagate cancel to the listenable future  
        boolean result = listenableFuture.cancel(mayInterruptIfRunning);  
        super.cancel(mayInterruptIfRunning);  
        return result;  
    }  
};  

What does this syntax means? Is this method overriding a method in the class without extending it?

borjab
  • 11,149
  • 6
  • 71
  • 98

2 Answers2

1

It's an anonymous class (one of the nested class types). Please also refer to the Java tutorial - Classes and Objects for further class types, if you are interested in them.

Roland
  • 22,259
  • 4
  • 57
  • 84
1

This block of code creates an anonymous subclass of CompletableFuture. This anonymous subclass overrides the cancel(bool) method with a new implementation. An anonymous subclass is equivalent to creating a new class that extends CompleteableFuture with the caveat that it isn't straightforward to re-use this new subclass somewhere else.

@Override is not strictly necessary in this case but it provides you several benefits, as described by the answer to this question:

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

Community
  • 1
  • 1
Alec Gorge
  • 17,110
  • 10
  • 59
  • 71