What is the purpose of modifying protected access in Java? In what situations should I use it?

Asked

Viewed 210 times

2

Regarding access modifiers in Java, what is the purpose of the modifier protected? What is its purpose in practice?

  • Yeah, now that I’ve seen the link.

1 answer

1

Default: You have access to a default attribute (identified by the absence of modifiers) all classes that are in the same package as the class that has the attribute.

Protected: This is the one that gets the most people, it is practically equal to the default, with the difference that if a class (even if it is outside the package) extends the class with the protected attribute, it will have access to it. So the access is by parcel and by inheritance.

Author: @Rodrigo-Sasaki

Link: What is the difference between public, default, protected and private modifiers?


Use case

In a class: Use in a class when you want to hide it from packages other than your current one and your package’s children.

In an attribute: When there is a need to directly obtain the attribute "without the use of getters and setters" by classes that are in the same package, or that inherit from the current class.

In a method: Use when you need to protect your access method from outside of your package or from classes that do not inherit the behavior.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.