Challenge - 5 Problems
Encapsulation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2: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."); } }
Attempts:
2 left
π‘ Hint
Check how the setAge method handles negative values.
β Incorrect
The setAge method only updates the age if the new value is positive. Since -5 is not positive, the age remains 30.
π§ Conceptual
intermediate1:30remaining
Why Use Private Fields in Encapsulation?
Why is it a best practice to declare class fields as private when using encapsulation in Java?
Attempts:
2 left
π‘ Hint
Think about how encapsulation protects data integrity.
β Incorrect
Private fields restrict direct access, so the class controls how data is accessed or changed, which helps maintain data integrity.
π§ Debug
advanced2: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; } } }
Attempts:
2 left
π‘ Hint
Encapsulation means hiding data from outside direct access.
β Incorrect
The balance field is public, so any code can change it directly, bypassing validation and control.
π Syntax
advanced1:30remaining
Correct Setter Method Syntax for Encapsulation
Which setter method correctly follows encapsulation best practices in Java?
Java
private int score;
Attempts:
2 left
π‘ Hint
A setter should accept a parameter and update the private field correctly.
β Incorrect
Option A correctly takes a parameter and assigns it to the private field using 'this' to avoid confusion.
π Application
expert2: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; }
Attempts:
2 left
π‘ Hint
Consider Java's access levels: private, protected, public, and default (package-private).
β Incorrect
Only the public field 'color' is accessible directly from any outside class. 'year' is protected (accessible in subclasses and package), 'owner' is package-private (default), and 'model' is private.