[post-views]
In this lesson, you will learn
To achieve encapsulation in Java:
package ch9;
class Person {
private String name; // Private variable, hidden from other classes
private int age; // Private variable, hidden from other classes
// Getter method for name to read value
public String getName() {
return name;
}
// Setter method for name to modify value
public void setName(String newName) {
name = newName;
}
// Getter method for age to read value
public int getAge() {
return age;
}
// Setter method for age to modify value
public void setAge(int newAge) {
if(newAge > 0) { // Simple validation
age = newAge;
}
}
}
public class PersonMain {
public static void main(String[] args) {
Person person = new Person();
person.setName("John"); // Setting the name using setter
person.setAge(30); // Setting the age using setter
System.out.println("Name: " + person.getName()
+", Age: " + person.getAge()); // Reading values using getters
}
}
Output
Name: John, Age: 30
Explanation
Person
class has two private variables: name
and age
.setName
and setAge
methods to modify the values of name
and age
, respectively. This is an example of write properties.getName
and getAge
methods to read the values of name
and age
, respectively. This is an example of read properties.
Through encapsulation, the actual representation of internal state is hidden from the outside, only allowing access through these public methods.
This way, you can ensure that Person
objects are always in a consistent state and protect their internal data from unauthorized access.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.