<aside>
☕
L1.3 — Encapsulation & Constructors introduces the first core principle of OOP: encapsulation, covering how to protect data using access modifiers, implement getters/setters for controlled access, and create constructors to properly initialize objects.
</aside>
📋 At a Glance
- [ ] Review the difference between public and private access modifiers
- [ ] Practice writing getter and setter methods with validation
- [ ] Understand when and why to use the
this keyword
- [ ] Master constructor syntax and overloading rules
- [ ] Remember the default constructor behavior
- [ ] Apply the "always start with private" principle
- [ ] Practice creating objects with different constructor signatures
- [ ] Understand the benefits of encapsulation for code maintenance
1. What is Encapsulation?
Encapsulation is one of the three core principles of Object-Oriented Programming. It involves:
- Bundling data with methods - Combining related data (properties) and the methods that operate on that data into a single class
- Controlling access - Preventing direct access to internal data from external classes
- Providing clean interfaces - Offering controlled ways to interact with the object through public methods
The Problem Without Encapsulation
Consider this simple Person class:
public class Person {
public String name;
public int age;
public void tell() {
System.out.println("Name: " + name + ", Age: " + age);
}
}