Bird
Raised Fist0
Javaprogramming~20 mins

Encapsulation best practices in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Encapsulation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Encapsulation with Private Fields
What is the output of this Java code that uses encapsulation with private fields and public getters/setters?
Java
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }

    public static void main(String[] args) {
        Person p = new Person("Alice", 30);
        p.setAge(-5);
        System.out.println(p.getName() + " is " + p.getAge() + " years old.");
    }
}
ACompilation error due to private fields.
BAlice is 30 years old.
CAlice is -5 years old.
DRuntime error due to invalid age.
Attempts:
2 left
πŸ’‘ Hint
Check how the setAge method handles negative values.
🧠 Conceptual
intermediate
1:30remaining
Why Use Private Fields in Encapsulation?
Why is it a best practice to declare class fields as private when using encapsulation in Java?
ATo allow subclasses to access fields directly without getters or setters.
BTo make the fields accessible from any class without restrictions.
CTo prevent direct access and modification from outside the class, ensuring control over data.
DTo improve the speed of the program by avoiding method calls.
Attempts:
2 left
πŸ’‘ Hint
Think about how encapsulation protects data integrity.
πŸ”§ Debug
advanced
2:00remaining
Identify the Encapsulation Violation
Which option shows a violation of encapsulation best practices in Java?
Java
public class BankAccount {
    public double balance;

    public BankAccount(double balance) {
        this.balance = balance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}
AMaking the balance field public allows direct modification from outside the class.
BProviding a deposit method to update balance.
CChecking if deposit amount is positive before adding.
DUsing a constructor to set the initial balance.
Attempts:
2 left
πŸ’‘ Hint
Encapsulation means hiding data from outside direct access.
πŸ“ Syntax
advanced
1:30remaining
Correct Setter Method Syntax for Encapsulation
Which setter method correctly follows encapsulation best practices in Java?
Java
private int score;
Apublic void setScore(int score) { this.score = score; }
Bpublic int setScore(int score) { this.score = score; return score; }
Cpublic void setScore() { score = 10; }
Dvoid setScore(int score) { score = score; }
Attempts:
2 left
πŸ’‘ Hint
A setter should accept a parameter and update the private field correctly.
πŸš€ Application
expert
2:00remaining
Number of Accessible Fields After Encapsulation
Given this class, how many fields are accessible directly from outside the class without using getters or setters?
Java
public class Car {
    private String model;
    protected int year;
    public String color;
    String owner;
}
A4
B2
C3
D1
Attempts:
2 left
πŸ’‘ Hint
Consider Java's access levels: private, protected, public, and default (package-private).

Practice

(1/5)
1.

What is the main purpose of encapsulation in Java?

easy
A. To hide the internal data of a class and control access to it
B. To make all variables public so they can be accessed anywhere
C. To allow direct access to class variables without methods
D. To write code faster by skipping method definitions

Solution

  1. Step 1: Understand encapsulation concept

    Encapsulation means hiding data inside a class to protect it from outside access.
  2. Step 2: Identify the purpose of encapsulation

    It controls how data is accessed or changed using getter and setter methods.
  3. Final Answer:

    To hide the internal data of a class and control access to it -> Option A
  4. Quick Check:

    Encapsulation = Data hiding and controlled access [OK]
Hint: Encapsulation means hiding data and controlling access [OK]
Common Mistakes:
  • Thinking encapsulation means making variables public
  • Confusing encapsulation with inheritance
  • Believing encapsulation allows direct variable access
2.

Which of the following is the correct way to declare a private variable in a Java class?

class Person {
? String name;
}
easy
A. private
B. public
C. protected
D. static

Solution

  1. Step 1: Recall Java access modifiers

    Private variables are declared with the keyword private to hide them inside the class.
  2. Step 2: Check the options

    Only private hides the variable from outside access, others allow wider access.
  3. Final Answer:

    private -> Option A
  4. Quick Check:

    Private keyword hides variables [OK]
Hint: Use 'private' to hide variables inside class [OK]
Common Mistakes:
  • Using public instead of private for encapsulation
  • Confusing protected with private
  • Using static which controls memory, not access
3.

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());
}
}
medium
A. Runtime error
B. Tesla
C. Compilation error
D. null

Solution

  1. Step 1: Understand private variable access

    The variable model is private but accessed via the public getter getModel().
  2. Step 2: Check the output of getModel()

    The getter returns the string "Tesla", so printing it outputs "Tesla".
  3. Final Answer:

    Tesla -> Option B
  4. Quick Check:

    Getter returns private variable value [OK]
Hint: Private data accessed via public getter returns value [OK]
Common Mistakes:
  • Expecting direct access to private variable
  • Thinking code causes compilation error
  • Confusing output with null or error
4.

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;
}
}
medium
A. The balance variable should be public
B. The getter method should be private
C. The setter method does not update the class variable correctly
D. The setter method should return a value

Solution

  1. Step 1: Analyze the setter method

    The setter uses balance = balance; which assigns the parameter to itself, not the class variable.
  2. Step 2: Understand correct assignment

    To update the class variable, use this.balance = balance; to refer to the instance variable.
  3. Final Answer:

    The setter method does not update the class variable correctly -> Option C
  4. Quick Check:

    Use 'this' to assign parameter to instance variable [OK]
Hint: Use 'this' to assign setter parameter to class variable [OK]
Common Mistakes:
  • Forgetting 'this' keyword in setter
  • Making getter private which breaks access
  • Expecting setter to return a value
5.

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?

hard
A. Make grade public and check the value before assigning
B. Make grade static and assign directly
C. Use a protected grade variable and no setter
D. Use a private grade variable with a setter that validates the value

Solution

  1. Step 1: Understand encapsulation for validation

    Encapsulation allows controlling how variables are set by using private variables and setters with checks.
  2. Step 2: Choose the best practice

    Using a private variable with a setter that validates the input ensures grade stays between 0 and 100.
  3. Final Answer:

    Use a private grade variable with a setter that validates the value -> Option D
  4. Quick Check:

    Setters with validation keep data safe [OK]
Hint: Validate data inside setter to protect private variables [OK]
Common Mistakes:
  • Making variables public and trusting external code
  • Skipping validation in setter
  • Using static which shares data across all instances