Encapsulation helps hide “sensitive” data from being accessed directly from outside of the Java class. This is achieved by:
- Declare attributes as private
- Provide public getter and setter methods to retrieve and update those private attributes
Example:
public class Car {
private String make;
private String model;
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public static void main(String[] args) {
Car car = new Car();
car.setMake("Toyota");
car.setModel("Camry");
System.out.println(car.getMake());
System.out.println(car.getModel());
}
}