Encapsulation is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
In encapsulation, you never expose your data to an external party. Which makes your application secure.
Java encapsulation is referred as data hiding. But more than data hiding, encapsulation concept is meant for better management or grouping of related data.
With encapsulation, developers can change one part of the code easily without affecting other.
If a data member is declared "private", then it can only be accessed within the same class. No outside class can access data member of that class. If you need to access these variables, you have to use public "getter" and "setter" methods.
The get method returns the variable value, and the set method sets the value.
private String name; // private = restricted access
// Getter public String getName() {
return name;
}
// Setter public void setName(String newName) {
this.name = newName;
}
}
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error System.out.println(myObj.name); // error }
}
- declare class variables/attributes as private (only accessible within the same class)
- provide public setter and getter methods to access and update the value of a private variable
In encapsulation, you never expose your data to an external party. Which makes your application secure.
Java encapsulation is referred as data hiding. But more than data hiding, encapsulation concept is meant for better management or grouping of related data.
With encapsulation, developers can change one part of the code easily without affecting other.
If a data member is declared "private", then it can only be accessed within the same class. No outside class can access data member of that class. If you need to access these variables, you have to use public "getter" and "setter" methods.
The get method returns the variable value, and the set method sets the value.
Example:
public class Person {private String name; // private = restricted access
// Getter public String getName() {
return name;
}
// Setter public void setName(String newName) {
this.name = newName;
}
}
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error System.out.println(myObj.name); // error }
}
Example explained
The
get
method returns the value of the variable name
.
The
set
method takes a parameter (newName
) and assigns it to the name
variable. The this
keyword is used to refer to the current object.
However, as the
name
variable is declared as private
, we cannot access it from outside this class:
0 comments:
Post a Comment