Welcome to the Java Encapsulation Quiz! In this quiz, we have compiled 25 top multiple-choice questions (MCQs) covering Java Encapsulation, data hiding, access modifiers, and modern Java Records.
Whether you are preparing for technical interviews, studying for Java certifications, or brushing up on OOP design principles, this assessment tests both conceptual understanding and real-world code analysis.
Put your skills to the test, analyze tricky edge cases, and discover where your Java OOP expertise stands!
public so any external class can directly read and modify them.private and providing public getter and setter methods to control access.static and removing instance variables entirely from the class.private and providing public getter and setter methods to control access.Explanation:
- A: Incorrect. Declaring fields as public breaks encapsulation because external classes can directly mutate the object’s internal state without validation or boundary checks.
- B: Correct. Encapsulation binds data and code into a single unit. Restricting direct access using private variables while offering controlled access via public getters and setters preserves data integrity.
- C: Incorrect. Marking methods static associates them with the class rather than individual instances, which is unrelated to encapsulating instance state.
- D: Incorrect. Java does not support multiple class inheritance (extends A, B), and inheritance models an “is-a” relationship rather than state hiding.
public class Employee {
private final int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
How does this implementation apply encapsulation to the id field?
Encapsulation allows selective access control. By declaring a field private and providing only a public getter (and no setter), the field becomes effectively read-only to external code.
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
this.balance = 0.0;
}
}
public double getBalance() {
return this.balance;
}
// Line to complete
}Which of the following method implementations properly provides a setter for balance while preserving encapsulation and preventing invalid account states?
A.
public void setBalance(double amount) {
this.balance = amount;
}B.
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
} else {
throw new IllegalArgumentException("Deposit amount must be positive.");
}
}C.
private void setBalance(double balance) {
this.balance = balance;
}D.
private void setBalance(double balance) {
this.balance = balance;
}public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
} else {
throw new IllegalArgumentException("Deposit amount must be positive.");
}
}Encapsulation is not just about writing standard getters and setters; it is about protecting an object’s internal invariant state through controlled, validated mutator methods with clear domain logic (such as deposit).
class Student {
private int age;
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public int getAge() {
return this.age;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.age = 20;
System.out.println(s.getAge());
}
}In Java, when a variable is marked as private, it is hidden from other classes. The Main class cannot see or change s.age directly. The Java compiler stops this and throws an error: age has private access in Student. To change the age correctly, you must use the setter method: s.setAge(20).
class Rectangle {
private int length;
public void setLength(int length) {
length = length;
}
public int getLength() {
return length;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rect = new Rectangle();
rect.setLength(15);
System.out.println(rect.getLength());
}
}Explanation:
- A: Incorrect. The value 15 was not saved into the object’s field because the method parameter shadowed (hid) the instance variable.
- B: Correct. In the setLength method, the parameter name length is the same as the class variable length. Writing length = length; simply assigns the parameter value to itself and does not update the object’s variable. Since the object’s length was never changed, it keeps its default int value, which is 0. To fix this and store 15, you should write this.length = length;.
- C: Incorrect. length = length; is valid Java syntax, so the code compiles without any compiler errors.
- D: Incorrect. No exceptions are thrown during execution.
boolean field named active?Explanation:
- A: Incorrect. While
getActive()works and compiles in Java, standard conventions specifically recommend using theisprefix forbooleanproperties instead ofget. - B: Correct. In standard Java naming rules (JavaBeans), getter methods for
booleanvariables should start withis(likeisActive()orisEligible()). This makes the code sound like a natural yes/no question when reading it, making your code easier to understand and compatible with Java frameworks. - C: Incorrect.
checkActive()is not a standard getter naming pattern in Java. - D: Incorrect.
hasActive()does not follow the standard getter naming convention for a primitivebooleanvariable.
Explanation:
- A: Incorrect. Public variables can be changed by anyone without any check or restriction.
- B: Correct. When fields are private, outside code must use setter methods to change them. Inside these setter methods, you can write simple
ifstatements (e.g., checking ifage > 0) to reject bad or invalid input before saving it. - C: Incorrect. The
finalkeyword makes a variable unchangeable, but it does not provide custom validation logic for updates. - D: Incorrect. Return types do not control whether data is validated or protected.
Explanation:
- A: Correct. Encapsulation is often referred to as “data hiding” because it hides the internal details and variables of a class from outside interference and misuse.
- B: Incorrect. Code duplication means writing the same code multiple times, which is a bad programming practice.
- C: Incorrect. Method overloading means having multiple methods with the same name but different parameters (polymorphism).
- D: Incorrect. Dynamic dispatch is related to runtime polymorphism and method overriding, not data hiding.
Explanation:
- A: Incorrect. Java does not force you to write setters. Classes without setters compile completely fine.
- B: Correct. When you hide a variable with
privateand provide only a getter method, outside code can only view (read) the value. Because there is no setter method, no one from the outside can modify (write) the value after the object is created. - C: Incorrect. Outside classes cannot access private fields directly.
- D: Incorrect. Java never automatically adds setter methods for you.
Explanation:
- A: Correct. If you provide only setter methods, external classes can supply or update the data, but they have no way to retrieve or inspect the stored value directly. This creates a write-only property.
- B: Incorrect. Immutable means an object cannot be changed after creation. Adding setters makes it mutable (modifiable).
- C: Incorrect. Getters are not mandatory in Java syntax.
- D: Incorrect. Private variables can never be directly read by external classes.
Explanation:
- A: Incorrect. Encapsulation is a design principle for clean architecture; it does not automatically double execution speed.
- B: Correct. Since outside code interacts only through public methods (like getters and setters), you can freely change the internal variable names, data types, or algorithms inside the class without affecting or breaking any outside code.
- C: Incorrect. Encapsulated code still requires thorough testing.
- D: Incorrect. Encapsulation has nothing to do with automatic database management.
Consider this code:
public class User {
private String password;
public void setPassword(String password) {
if (password != null && password.length() >= 8) {
this.password = password;
}
}
}Why is keeping the password field private better than making it public?
Explanation:
- A: Incorrect. Private fields are not directly accessible by subclasses either.
- B: Correct. Making
passwordprivate means outside code cannot directly assign a weak password likeuser.password = "123". It is forced to go throughsetPassword(), which enforces the minimum length rule. - C: Incorrect. Making a variable private does not automatically encrypt it.
- D: Incorrect. The private modifier prevents outside classes from bypassing the method and its checks.
Explanation:
- A: Incorrect.
publicis the most open modifier, accessible from any class in any package. - B: Incorrect.
protectedallows access to classes in the same package and subclasses in other packages. - C: Incorrect. Default access allows any class in the same package to access the member.
- D: Correct. The
privatemodifier is the strictest access level in Java. A private member can only be accessed within the exact same class where it is declared, giving you total control over the data.
Explanation:
- A: Incorrect. A class with only static methods is typically a utility class (like
Math), not an example of full encapsulation. - B: Correct. In Java, a class is considered “tightly” or “fully” encapsulated when every single instance variable is marked
private, and interaction with those fields is handled exclusively through standard public getter and setter methods. - C: Incorrect. Implementing interfaces is unrelated to field-level encapsulation.
- D: Incorrect. Declaring variables public directly violates encapsulation.
Consider the following class:
public class ScoreTracker {
private int score;
public void addPoints(int points) {
if (points > 0) {
this.score += points;
}
}
public int getScore() {
return this.score;
}
}Why is providing an addPoints method better for encapsulation than a standard setScore(int score) method?
Explanation:
- A: Correct. Good encapsulation exposes meaningful actions rather than raw variables. An
addPoints()method ensures that points can only increase naturally according to game rules, rather than allowing any outside code to overwrite the score directly. - B: Incorrect. Setters can take integer parameters with no issue.
- C: Incorrect. There is no significant performance difference between the two methods.
- D: Incorrect. The method does not alter the variable’s static or instance nature.
Explanation:
- A: Incorrect. You must explicitly write the
privatekeyword to make a member private. - B: Incorrect. You must explicitly write
protected. - C: Correct. When you write no modifier (e.g.,
int score;), Java assigns default access (package-private). This allows any other class in the exact same package/folder to see and modify the field, which can unintentionally bypass encapsulation if not planned. - D: Incorrect.
publicmust be explicitly declared for class fields.
Explanation:
- A: Correct. Because an encapsulated class manages its own state and validates all inputs internally, you can easily write unit tests for it and reuse it in other applications with confidence that its internal state will stay valid.
- B: Incorrect. Encapsulation is a source-code design concept, not a compilation or packaging tool.
- C: Incorrect. Encapsulation does not convert objects into singletons.
- D: Incorrect. Constructors are still used to initialize encapsulated objects properly.
Explanation:
- A: Incorrect.
superrefers to members of the parent (super) class. - B: Correct. The
thiskeyword refers to the current object instance. When a method parameter has the exact same name as an instance variable (e.g.,int age), writingthis.age = age;clearly tells Java to assign the parameter value to the object’s instance variable. - C: Incorrect.
staticdenotes class-level variables or methods. - D: Incorrect.
finalmarks a variable or method as unchangeable/un-overridable.
Look at the following code snippet:
public class Temperature {
private double celsius;
public void setCelsius(double celsius) {
if (celsius >= -273.15) {
this.celsius = celsius;
} else {
System.out.println("Invalid temperature: Below Absolute Zero!");
}
}
public double getFahrenheit() {
return (this.celsius * 9 / 5) + 32;
}
}What concept does the getFahrenheit() method demonstrate?
Explanation:
- A: Incorrect. Notice there is no separate
fahrenheitvariable stored, so no extra memory is wasted. - B: Correct. Encapsulation allows you to provide useful getters that compute values on the fly. The caller gets Fahrenheit seamlessly, while the class keeps only a single source of truth (
celsius) internally. - C: Incorrect. Returning a computed value does not violate encapsulation.
- D: Incorrect. There is no inheritance or method overriding happening here.
Explanation:
- A: Incorrect. Returning an array or list reference compiles without any warnings or errors.
- B: Correct. If you return a direct reference to a mutable object (like a list or array), external code can add or remove items from it directly. To protect encapsulation, you should return a defensive copy or an unmodifiable view (e.g.,
Collections.unmodifiableList(...)). - C: Incorrect. The garbage collector does not delete referenced objects.
- D: Incorrect. Java will not change modifiers automatically.
Explanation:
- A: Incorrect. Public variables provide zero encapsulation and can be changed anytime.
- B: Correct. An immutable class cannot be modified after creation. By setting private final fields in the constructor and providing only getter methods, the object’s state is completely protected and cannot be altered by anyone.
- C: Incorrect. Static members belong to the class, not to encapsulated instances.
- D: Incorrect. Having setters makes the object mutable (changeable).
public and adding comments asking other developers “Please do not modify directly”?Explanation:
- A: Correct. Comments are just human text and cannot enforce rules. Encapsulation uses language-level rules (the
privatekeyword) so the compiler itself stops anyone from modifying data incorrectly. - B: Incorrect. Comments are stripped out during compilation and do not increase bytecode size.
- C: Incorrect. Access modifiers have no effect on memory size.
- D: Incorrect. Comments can be written anywhere in Java source code.
Explanation:
- A: Incorrect. Setters typically set a value and do not return an integer.
- B: Incorrect. Setters do not return String by convention.
- C: Correct. By standard Java convention, a setter method’s job is simply to update the value of an internal variable. Therefore, it takes a parameter and returns
void(nothing). - D: Incorrect. While some custom methods return a boolean indicating success, standard JavaBeans setters return
void.
Explanation:
- A: Correct. In modern Java, a
recordis a concise way to create an immutable class. Java automatically marks fields as private and final and provides clean accessor methods for you, reducing boilerplate code while maintaining strong encapsulation. - B: Incorrect. Records have nothing to do with multimedia recording.
- C: Incorrect. Record fields are implicitly final and private.
- D: Incorrect. Records are language constructs, not garbage collectors.
Explanation:
- A: Correct. This is the definition of encapsulation: grouping related data and methods together inside a class (“capsule”) and using access modifiers to protect the data from unauthorized direct modification.
- B: Incorrect. This describes multiple inheritance, which Java does not support for classes.
- C: Incorrect. Bytecode generation is the job of the Java compiler (javac).
- D: Incorrect. Global public access is the opposite of encapsulation.







