Encapsulation & access modifiers
Computer Science · Java
Question 1 of 10
0How many public top-level classes may a single Java source file contain?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Encapsulation & access modifiers explained
Encapsulation means keeping an object's data private and letting other code use it only through methods the class controls. Access modifiers set who can see a member. The four levels are private, package-private (the default, with no keyword), protected and public.
A private field can be used only inside its own class. A method inside the class can check and then change the value, so the class can reject bad input, such as a deposit of zero or less. Package-private members are visible to classes in the same package. protected members are visible within the package and to subclasses, and public members are visible everywhere. A good habit is to keep fields private and make public only the methods that other code needs. Encapsulation also lets you change the internal representation later without breaking code that uses the class.
class Account {
private int balance;
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
public int getBalance() {
return balance;
}
}
Worked example
Trace the class above with an Account object named a.
- balance starts at 0.
- a.deposit(50) passes the check, so balance becomes 50.
- a.deposit(-20) fails the check, so balance stays 50.
- Code in another class cannot write a.balance, because balance is private. a.getBalance() returns 50.
What you will practise
100 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Encapsulation:
- The private modifier:
- The public modifier:
- Getters and setters:
- The protected modifier:
- In Java, a member with no access modifier (package-private) is accessible:
- Which keyword stops a class from being subclassed?
- Which keyword marks a member as belonging to the class rather than to each object?
…and 92 more.