Reputation: 683
I'll preface this with I believe I understand how the access level modifiers work in Java. My question has to do with the difference between protected and package-private (no modifier) when used in a final class.
From my understanding:
If you declare a class as final you aren't able to extend it, which means that there won't be any subclasses of it
If you don't add a modifier to a method (package-private) it is visible only within its own package
If you declare a method protected it can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package
My question is if your class is a final class, is there any difference between package-private and protected? The final modifier makes it so that there can't be any subclasses, so it doesn't seem like there can be a subclass in another package. Which means that in either case it will just be visible in its own package.
In a final class is there a difference between the two?
If there is no difference is one supposed to be used over the other or does it not matter?
Upvotes: 5
Views: 3818
Reputation: 96
If we apply the final restriction (prevent inheritance) to the classical table of access modifiers, we get:
So, from the logic point of view (if we study it as a Karnaugh map) both modifiers package and protected are equivalent (if final restriction is aplied).
In a second thinking, we can question which one has better performance and which one is closer to the good design principles. Taking into account the answer of erickson, if the final modifier is aplied, both cases should have de same performance at runtime. But from the formal point of view declare it as protected, if it is not possible to inherit, has no sense. So, package (also called default or without modifier) should be de right choose.
Upvotes: 3
Reputation: 147164
If there cannot be any subclasses, there is no advantage in going for protected
over the default.
However, protected
members and constructors will appear in API docs. This is probably not intended. Fun fact: java.net.URL
used to have a protected
methods that was deprecated when replaced by another. Both have now been removed.
In general, make members either public
(not fields) or private
.
Upvotes: 1
Reputation: 79580
Unless and until it comes to subclassing, there is no difference between protected
and no modifier. Since you are going to restrict subclassing by using final
, it doesn't make sense to use protected
, even though it is correct to do so.
Upvotes: 0