Why can't the annotation @SafeVarargs
be applied to non-final instance methods?
Asked
Active
Viewed 2,899 times
19

MC Emperor
- 22,334
- 15
- 80
- 130

Kumar Abhinav
- 6,565
- 2
- 24
- 35
-
1@mabe That is not a duplicate: private methods are implicitly final, therefor it is different from asking why a method must be final when using `@SafeVarargs`, or why private methods must also be declared private (as they are already implicitly final). – Mark Rotteveel Jul 28 '14 at 12:35
-
@MarkRotteveel It is marked as a **possible** duplicate. And if you look at the given answer in that link you'll see that it is clearly mentioned too. *I think the real reason for the requirement of final or static was to force that the method could not be overridden, and thus a subclass couldn't tamper with data in a way that made the `@SafeVarargs` annotation useless on the definition of the method.* – maba Jul 28 '14 at 12:39
-
1@maba Good point, the answer might apply here, but the question doesn't ;) – Mark Rotteveel Jul 28 '14 at 12:50
1 Answers
24
If you declare @SafeVarargs
, then you must be sure it is actually safe. If a method is non-final, it can be overridden in a subclass. That override might not be safe.
By requiring that the method is final
, the developer can guarantee that the declaration he made (namely that its varargs use is safe) is actually always true (provided of course that the developer actually provided a safe varargs method), and that it wasn't actually broken by a subclass incorrectly reimplementing the method.

Mark Rotteveel
- 100,966
- 191
- 140
- 197
-
1Basically Java wants to ensure strong behavioral subtyping as prescribed by the [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle#Principle). Because it is impossible for the compiler to check all subclass implementations that could ever be written (unless the method is final and thus there are no subclass implementations for it whatsoever) it doesn't allow to use the `@SafeVarargs` – neXus Nov 10 '17 at 14:45