private
keyword is the main actor for encapsulation. It makes the class attributes inaccessible directly from outside the class. The public
keyword allows the class attributes to be accessed from outside the class.public class Employee {
String name;
int age;
}
In this example, the class attributes (name and age) can be accessed directly, which is not a good practice.
public class Employee {
private String name;
private int age;
//Getter for name
public String getName() {
return name;
}
//Setter for name
public void setName(String newName) {
this.name = newName;
}
//Getter for age
public int getAge() {
return age;
}
//Setter for age
public void setAge(int newAge) {
this.age = newAge;
}
}
In this example, the class attributes (name and age) are declared as private. They can't be accessed directly from outside the class. We have provided public getter and setter methods to access and modify these variables.
Next steps for learning:
- Explore other OOP concepts like Inheritance, Polymorphism, and Abstraction.
- Practice writing encapsulated classes and objects in Java.
Additional resources:
- Oracle Java Documentation
- Java Encapsulation (GeeksforGeeks)
Exercise 1: Create a Person
class with private attributes: name
and age
. Then provide public getters and setters to manipulate these variables. Create a Person
object in a main
method and demonstrate getting and setting the attributes.
Exercise 2: Create a BankAccount
class with private attributes: accountNumber
and balance
. Provide public methods for deposit
, withdraw
, and checkBalance
. Make sure balance cannot go negative during withdrawal.
Tips for further practice:
- Try to create more complex classes with more attributes.
- Practice creating classes where some attributes are read-only (only provide getters) and some are write-only (only provide setters).
- Try encapsulating behavior as well (methods) in addition to the data (variables).