Module 11: Encapsulation & PackagesBeginner22 min read
Encapsulation, Access Modifiers & Packages
Master private fields, validated getters/setters, all 4 Java access levels, user-defined packages, and import statements.
Key Takeaways & Core Concepts
- (no keyword) | Yes | Yes | No | No |
- Packages (
package com.codezov.service;) mirror directory structure, prevent class name collisions, and enable package-private encapsulation. - Static Imports (
import static java.lang.Math.PI;) let you reference static constants/methods without qualifying the class name (use sparingly to keep code readable).
Encapsulation & Data Hiding
Encapsulation bundles data (private fields) with validated methods (public getters/setters). By hiding internal fields, you guarantee class invariants—for instance, ensuring a BankAccount balance can never become negative or bypass audit logging.
Encapsulated BankAccount with Validation
1class BankAccount {
2 private double balance;
3
4 public void deposit(double amount) {
5 if (amount <= 0) {
6 System.out.println("Rejected invalid deposit: " + amount);
7 return;
8 }
9 balance += amount;
10 }
11
12 public double getBalance() {
13 return balance;
14 }
15}
16
17public class Main {
18 public static void main(String[] args) {
19 BankAccount acc = new BankAccount();
20 acc.deposit(1500);
21 acc.deposit(-200);
22 System.out.println("Balance: " + acc.getBalance());
23 }
24}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
24 lines
Note: Keeping `balance` private ensures all mutations pass through `deposit()` validation.
All 4 Access Modifiers
| Modifier | Same Class | Same Package | Subclass (Other Pkg) | Everywhere |
|---|---|---|---|---|
private | Yes | No | No | No |
| default (no keyword) | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public | Yes | Yes | Yes | Yes |
Packages & Static Imports
- Packages (
package com.codezov.service;) mirror directory structure, prevent class name collisions, and enable package-private encapsulation. - Static Imports (
import static java.lang.Math.PI;) let you reference static constants/methods without qualifying the class name (use sparingly to keep code readable).
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)