Concept
What are the visibility levels used to protect Java data?
ComputerScienceOne / Data Visibility
"Recall that encapsulation involves not only the grouping of data, but the protection of data. To provide for the protection of data, Java defines several visibility keywords that specify what segments of code can “see” the variables. Visibility in this context determines whether or not a segment of code can access and/or modify the variable’s value. Java defines four levels of visibility using they keywords public, protected and private (a fourth level is defined by the absence of any of these keywords). Each of these keywords can be applied to both member variables and member methods.\n\n• public – This is the least restrictive visibility level and makes the member variable visible to every class.\n\n• protected – This is a bit more restrictive and makes it so that the member variable is only visible to the code in the same class, same package, or any subclass of the class.\n\n• No modifier – the absence of any modifier means that the member variable is visible to any class in the same package. This is also referred to as the default or package protected visibility level.\n\n• private – this is the most restrictive visibility level, private member variables are only visible to instances of the class itself. As we’ll see later this also means that the member variables are visible between instances. That is, one instance can see another instance’s variables.\n\nTable 34.1 summarizes these four keywords with respect to their access levels. It is important to understand that protection in the context of encapsulation and does not involve protection in the sense of “security.” The protection is this context is a design principle. Limiting the access of variables only affects how the rest of the code base interacts with our class and its data. Encapsulation can easily be “broken” by other\n\nSubclasses are involved with inheritance, another object-oriented programming concept that we will not discuss here)."
Related Ideas
- How does PHP visibility protect class data?ComputerScienceOne · Data Visibility
- How do accessor and mutator methods use this to access instance variables?ComputerScienceOne · Accessor & Mutator Methods
- How do accessor and mutator methods provide access to private member variables?ComputerScienceOne · Accessor & Mutator Methods
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- How does encapsulation group and protect related data?ComputerScienceOne · Encapsulation & Objects
- Why are getters, setters, and immutable member variables useful?ComputerScienceOne · Constructors
- How can getters and setters validate values before changing private variables?ComputerScienceOne · Accessor & Mutator Methods
- How should a class manage owned collections and avoid shallow copies?ComputerScienceOne · Composition