codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Subjects
🧩

OOP Concepts

23 chapters

1Procedural vs Object-Oriented2Classes, Objects, & Instantiation3Constructors & Destructors4Static Members & Methods5Encapsulation & Access Modifiers6Data Abstraction7Inheritance Types (Single, Multiple)8Compile-Time Polymorphism (Overloading)9Polymorphism & Interfaces10Run-Time Polymorphism (Overriding)11Virtual Functions & V-Tables12Interfaces & Abstract Classes13Generic Programming (Templates & Generics)14Exception Handling in OOP15SOLID Design Principles16Composition over Inheritance17Coupling & Cohesion18UML Diagrams Basics19Creational Patterns (Singleton, Factory)20Structural Patterns (Adapter, Decorator)21Behavioral Patterns (Observer, Strategy)22MVC Architecture Pattern23Object Serialization & Cloning
SubjectsOOP Concepts

Encapsulation & Access Modifiers

Updated 2026-05-05
2 min read

Encapsulation & Access Modifiers

Encapsulation is the first and arguably most important pillar of Object-Oriented Programming. It is the mechanism of wrapping the data (variables) and the code acting on the data (methods) together as a single unit, and then restricting direct access to some of the object's components.

1. The Concept of Encapsulation

Think of a capsule (pill). A capsule encases medicine inside a protective shell. You don't need to know the chemical formula inside; you just swallow it. Similarly, an encapsulated class hides its internal data behind a protective layer of methods.

The core principle: an object's data should NEVER be directly accessible from outside the object. All interaction with the data must happen through the object's own methods.

Without Encapsulation (Dangerous):

class BankAccount {
    public double balance; // Anyone can access this!
}

BankAccount acc = new BankAccount();
acc.balance = -999999; // A bug sets balance to negative. No validation!

With Encapsulation (Safe):

class BankAccount {
    private double balance; // Hidden from the outside world

    public void deposit(double amount) {
        if (amount > 0) { // Validation logic!
            this.balance += amount;
        }
    }

    public double getBalance() {
        return this.balance;
    }
}

BankAccount acc = new BankAccount();
// acc.balance = -999999;  // COMPILE ERROR! Cannot access private field.
acc.deposit(500); // The only way to modify balance is through the validated method.

2. Access Modifiers

Access Modifiers are keywords that control the visibility and accessibility of classes, methods, and variables. They are the enforcement mechanism for encapsulation.

Java Access Modifiers (from most to least restrictive):

  1. private: Accessible only within the same class. Not visible to any other class, not even subclasses. This is the default choice for all class attributes.
  2. default (no keyword): Accessible only within the same package. Not visible to classes in other packages.
  3. protected: Accessible within the same package, AND by subclasses (even if the subclass is in a different package).
  4. public: Accessible from absolutely anywhere. Any class in the entire project can access it.
ModifierSame ClassSame PackageSubclass (Diff Package)World
privateYesNoNoNo
defaultYesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

3. Getters and Setters

If all data is private, how does the outside world interact with it? Through Getter and Setter methods (also called Accessor and Mutator methods).

  • Getter: A public method that returns the value of a private variable.
  • Setter: A public method that sets the value of a private variable, often including validation logic.
class Employee {
    private String name;
    private int age;

    // Getter
    public String getName() {
        return this.name;
    }

    // Setter with validation
    public void setAge(int age) {
        if (age >= 18 && age <= 65) {
            this.age = age;
        } else {
            throw new IllegalArgumentException("Age must be between 18 and 65");
        }
    }
}

This pattern gives the class author complete, centralized control over how its data is read and modified, making debugging trivial compared to procedural code where any function could silently corrupt the data.



PreviousStatic Members & MethodsNextData Abstraction

Recommended Gear

Static Members & MethodsData Abstraction