initialZero
initialZero

Reputation: 6367

java @SafeVarargs why do private methods need to be final

I have a private method in an inner class which is private I would like to use the SafeVarargs annotation. However, I am required to either have a static or final method. Why does a private method need to be final as well? Isn't this redundant?

Upvotes: 25

Views: 2062

Answers (3)

user2485429
user2485429

Reputation: 567

From Java 9, You can apply @SafeVarargs to private methods also. Check this post to know where you can use @SafeVarargs from Java 9.

Upvotes: 0

chiperortiz
chiperortiz

Reputation: 4991

This feature is part of Project Coin 2 and will be avalaible in Java 9 coming July 2017.

It's call Accepting @SafeVarargs on private methods.

Link.

Upvotes: 6

MetroidFan2002
MetroidFan2002

Reputation: 29878

It is redundant, and you bring up an excellent point.

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.

But, although it is redundant, it's not that bad of a decision - many a time, programmers will make every method private as much as possible, and then slowly open the class up as needed. If this method is marked final when it is in private scope, then if the method has to be opened up, it can still have the @SafeVarargs annotation in place with only a change to the access level. If the final is removed intentionally, you'll get the compile time error, but if you had it already, whoever removes the private access (which may not be yourself, in a team-based environment) won't be confused as to why removing the "private" modifier suddenly makes the code no longer compile.

Upvotes: 18

Related Questions