strikerdude10
strikerdude10

Reputation: 683

Protected vs package-private in final class

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:

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

Answers (3)

Vladimir Bataller
Vladimir Bataller

Reputation: 96

If we apply the final restriction (prevent inheritance) to the classical table of access modifiers, we get:

Classic access modifiers table

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

Tom Hawtin - tackline
Tom Hawtin - tackline

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

Arvind Kumar Avinash
Arvind Kumar Avinash

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.

enter image description here

Upvotes: 0

Related Questions