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

2

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

    
asked by anonymous 27.09.2015 / 04:17

1 answer

1
  

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

     

Protected: This is the one that catches the most people, it is almost equal to the default, except that if a class (even though it is outside the package) extends the class with the protected attribute , she will have access to it. So access is per package and inheritance.

Author: @ rodrigo-sasaki

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

Use case

In a class: Use the in a class when you want to hide it from different packages of your current and children in your package.

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

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

    
27.09.2015 / 04:28