Java
Summary - Encapsulation
Combine private, getter and setter to write an Account class.
Summary - Encapsulation
In this group you learned encapsulation with private fields, getter and setter methods, package visibility and record definitions. Encapsulation protects data and prevents invalid assignments.
Now you will bring it all together: define a class, add private fields, write getters and setters, perform validation. Encapsulation is the foundation of robust class design.
Exercise Define BankAccount with encapsulation
Define a class BankAccount. Add a private double balance field. Write a public double getBalance() getter returning balance. Add a void deposit(double amount) method; its body runs if (amount > 0) balance += amount;. In main create a BankAccount instance, call deposit(500) and print the result of getBalance().
Show example solution
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(500);
System.out.println(acc.getBalance());
}
}
What comes next?
You learned encapsulation. In the next groups you will work with class-level data using static members, immutable values with constants and contracts with interfaces. These are the next layer of class design.
This group combined private, getters, setters, package visibility and record. These are the foundation of data protection. Next you will explore class-level shared fields and methods with static; you will work with data that belongs to the class beyond instances.
Exercise Define Temperature with encapsulation
Define a class Temperature. Add a private double celsius field. Write a public double getCelsius() getter returning celsius. Write a void setCelsius(double c) setter; its body runs if (c >= -273.15) celsius = c;. In main create a Temperature instance, call setCelsius(25.0) and print the result of getCelsius().
Show example solution
class Temperature {
private double celsius;
public double getCelsius() {
return celsius;
}
void setCelsius(double c) {
if (c >= -273.15) celsius = c;
}
public static void main(String[] args) {
Temperature t = new Temperature();
t.setCelsius(25.0);
System.out.println(t.getCelsius());
}
}
Test yourself
-
What does encapsulation provide?
- Data is protected
- Code runs faster
- Methods are hidden
- The class is deleted
Show answer
Data is protected — Data is protected — encapsulation ensures data integrity.
-
Complete the getter body
public double getBalance() {
____;
}
Show answer
public double getBalance() {
return balance;
}
Next lesson: static fields