Hey everyone!
In my previous post, I covered constructors, return methods, and comments — essential concepts in Java. Today, we’ll continue exploring Object-Oriented Programming (OOP) by learning about encapsulation, getters and setters, access modifiers, and why modifying values directly isn’t a good practice.
Encapsulation in Java
Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized direct access to them. Instead of allowing values to be changed freely, we use getters and setters to control access and ensure data integrity.
Why use encapsulation?
✅ Keeps data safe by limiting access.
✅ Provides better control over how data is modified.
✅ Makes your code easier to maintain.
Access Modifiers
Access modifiers define the visibility of classes, methods, and variables. Java has four main access modifiers:
-
public
: Accessible from anywhere. -
default
: Accessible within the same package -
protected
: Accessible within the same package and by subclasses -
private
: Accessible only within same class
Example of Encapsulation with Getters and Setters:
class Car {
// Private fields to ensure data protection
private String brand;
private int maxSpeed;
// Constructor to initialize values
public Car(String brand, int maxSpeed) {
this.brand = brand;
this.maxSpeed = maxSpeed;
}
// Getter method for the brand
public String getBrand() {
return brand;
}
// Setter method for the brand
public void setBrand(String brand) {
this.brand = brand;
}
// Getter method for maxSpeed
public int getMaxSpeed() {
return maxSpeed;
}
// Setter method for maxSpeed
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public void outputValues() {
System.out.println("Brand: " + brand);
System.out.println("Max Speed: " + maxSpeed);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("BMW", 250);
// Using getter to display values
System.out.println("Initial brand: " + car.getBrand());
// Using setter to update values
car.setBrand("Audi");
car.setMaxSpeed(300);
// Display updated values
car.outputValues();
}
}
Output:
Initial brand: BMW
Brand: Audi
Max Speed: 300
Why Avoid Direct Value Modification?
Directly changing field values bypasses important checks and logic that ensure data consistency. Using getters and setters allows you to:
✅ Add validation rules.
✅ Control how values are updated.
✅ Improve code flexibility and scalability.
Summary
✅ Encapsulation protects your data by using private fields.
✅ Getters and setters help control how data is accessed and modified.
✅ Access modifiers define what can be accessed from where.
Whats next
In the next post, we'll explore the topic of inheritance, method overriding, and polymorphism in Java.
To practice, I suggest writing your own class with private fields, using both getters and setters. Try experimenting with access modifiers to understand their behavior better.
Top comments (0)