DEV Community

Kanishka Shrivastava
Kanishka Shrivastava

Posted on

#java #oop #encapsulation #programming

Java Concepts I’m Mastering – Part 8: Encapsulation & Data Hiding

Continuing my journey of mastering Java fundamentals.

Today’s concept: Encapsulation — one of the core pillars of OOP.

What is Encapsulation?

Encapsulation means:

Wrapping data (variables) and methods (functions) together inside a class
and restricting direct access to data.

It protects the internal state of an object.

How Do We Achieve It?

Make variables private

Provide public getter and setter methods

Example

class Student {
    private String name;   // Data hidden

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Enter fullscreen mode Exit fullscreen mode

Now:


Student s = new Student();
s.setName("Kanishka");
System.out.println(s.getName());

Enter fullscreen mode Exit fullscreen mode

Direct access like s.name is not allowed.

Why is This Important?

Protects data from unwanted modification

Improves security

Makes code more maintainable

Allows validation inside setters

Example with validation:

public void setAge(int age) {
    if(age > 0) {
        this.age = age;
    }
}

Enter fullscreen mode Exit fullscreen mode

Now invalid data cannot enter the system.

What I Learned

Always keep variables private

Control access through methods

Encapsulation makes classes robust and secure

This concept is heavily used in real-world applications and frameworks.

Next in the series: Inheritance in Java (extends keyword)

Top comments (0)