Encapsulation
Learn how private fields and public methods can protect data inside classes.
Java Code
Study the example and understand what each part does.
class Account {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account();
account.deposit(5000);
System.out.println(account.getBalance());
}
}
Java code normally runs using the Java Development Kit on a computer, Android Studio or another Java development environment. This course page presents the code examples without pretending that the browser is running Java directly.
Expected Output / Result
5000.0
Finished this lesson?
Mark it complete to update your course progress.