D.2.4 Explain the advantages of encapsulation.
Encapsulation is language mechanism that restricts direct access to some of the class's components. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data or information hiding.
To encase in or as if in a capsule
To express in a brief summary
Encapsulation can be described as a protective measure that prevents the code and data from being accessed and manipulated by other code defined outside of the class.
Wrapping of data in a construct such that it hides its internal data (use of access modifiers, see list below)
Provide behaviour methods to control access of data in desired fashion (use of setter and getter methods)
Flexibility:
Makes it easy to model real-world entities – hence easy to understand and maintain
Control the way data is accessed or modified
Gives flexibility to the design: Provides the ability to implement code without breaking the code created by others.
Extensibility:
Makes the class easy to use for clients
Increase reusability
Maintainability:
Provides the easy to update or fix code without interfering with the usage others are making of the classes being maintained.
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
A language feature that enforces information hiding
Information hiding is the practice of hiding the details of a module with the goal of controlling access to the details
The bundling of data and actions in such a way that the logical properties of the data and actions are separated from the implementation details.
Each class encapsulates its data but shares their values through knowledge responsibilities/ through methods
Declare the variables of a class as private.
Provide public mutator/setter and accessor/getter methods to modify and view the variables values.
/**
*
* @author maanderson
*/
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.