Encapsulation helps keep data safe and organized inside a class. It hides details so others use the class easily without mistakes.
Encapsulation best practices in Java
Start learning this pattern below
Jump into concepts and practice - no test required
public class ClassName { private DataType variableName; public DataType getVariableName() { return variableName; } public void setVariableName(DataType variableName) { this.variableName = variableName; } }
Use private to hide variables inside the class.
Use public getter and setter methods to control access.
name variable and allows safe access through methods.public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class BankAccount { private double balance; public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; } } }
This program shows a car with a model and speed. Speed cannot be set to a negative number because of the check inside the setter method.
public class Car { private String model; private int speed; public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getSpeed() { return speed; } public void setSpeed(int speed) { if (speed >= 0) { this.speed = speed; } } public static void main(String[] args) { Car myCar = new Car(); myCar.setModel("Toyota"); myCar.setSpeed(50); System.out.println("Model: " + myCar.getModel()); System.out.println("Speed: " + myCar.getSpeed()); myCar.setSpeed(-10); // This will not change speed because of check System.out.println("Speed after invalid update: " + myCar.getSpeed()); } }
Always keep variables private to protect data.
Use getter and setter methods to add checks or rules when accessing data.
Do not expose variables directly to avoid accidental changes.
Encapsulation hides data inside classes using private variables.
Use getter and setter methods to control how data is accessed or changed.
This helps keep your code safe, clean, and easy to fix or improve later.
Practice
What is the main purpose of encapsulation in Java?
Solution
Step 1: Understand encapsulation concept
Encapsulation means hiding data inside a class to protect it from outside access.Step 2: Identify the purpose of encapsulation
It controls how data is accessed or changed using getter and setter methods.Final Answer:
To hide the internal data of a class and control access to it -> Option AQuick Check:
Encapsulation = Data hiding and controlled access [OK]
- Thinking encapsulation means making variables public
- Confusing encapsulation with inheritance
- Believing encapsulation allows direct variable access
Which of the following is the correct way to declare a private variable in a Java class?
class Person {
? String name;
}Solution
Step 1: Recall Java access modifiers
Private variables are declared with the keywordprivateto hide them inside the class.Step 2: Check the options
Onlyprivatehides the variable from outside access, others allow wider access.Final Answer:
private -> Option AQuick Check:
Private keyword hides variables [OK]
- Using public instead of private for encapsulation
- Confusing protected with private
- Using static which controls memory, not access
What will be the output of the following code?
class Car {
private String model = "Tesla";
public String getModel() {
return model;
}
}
public class Test {
public static void main(String[] args) {
Car car = new Car();
System.out.println(car.getModel());
}
}Solution
Step 1: Understand private variable access
The variablemodelis private but accessed via the public gettergetModel().Step 2: Check the output of getModel()
The getter returns the string "Tesla", so printing it outputs "Tesla".Final Answer:
Tesla -> Option BQuick Check:
Getter returns private variable value [OK]
- Expecting direct access to private variable
- Thinking code causes compilation error
- Confusing output with null or error
Identify the error in the following code related to encapsulation:
class BankAccount {
private double balance;
public void setBalance(double balance) {
balance = balance;
}
public double getBalance() {
return balance;
}
}Solution
Step 1: Analyze the setter method
The setter usesbalance = balance;which assigns the parameter to itself, not the class variable.Step 2: Understand correct assignment
To update the class variable, usethis.balance = balance;to refer to the instance variable.Final Answer:
The setter method does not update the class variable correctly -> Option CQuick Check:
Use 'this' to assign parameter to instance variable [OK]
- Forgetting 'this' keyword in setter
- Making getter private which breaks access
- Expecting setter to return a value
You want to create a class Student with a private variable grade that can only be set if the value is between 0 and 100. Which is the best way to implement this using encapsulation?
Solution
Step 1: Understand encapsulation for validation
Encapsulation allows controlling how variables are set by using private variables and setters with checks.Step 2: Choose the best practice
Using a private variable with a setter that validates the input ensuresgradestays between 0 and 100.Final Answer:
Use a private grade variable with a setter that validates the value -> Option DQuick Check:
Setters with validation keep data safe [OK]
- Making variables public and trusting external code
- Skipping validation in setter
- Using static which shares data across all instances
