QuizzesJava Encapsulation
beginner
java

Java Encapsulation

Test your understanding of encapsulation, getters/setters, data hiding, immutability, and JavaBeans conventions in Java.

20 minutes 20 questions Pass at 70%
Time Limit
20 minutes - timer starts when you begin
Change Answers Freely
Revisit and change any answer before submitting
Full Review After Submit
Correct answers and explanations shown for every question
Auto-submit on timeout
Quiz submits automatically when time runs out

Questions in this quiz

20 questions on Java Encapsulation. Work through them here, then start the quiz to answer them and see your score.

  1. 1.What is encapsulation in Java?

    • AWrapping data and the methods that operate on it together inside a class, and restricting direct access
    • BHiding the class from other packages
    • CMaking all fields public for easy access
    • DExtending one class from another
  2. 2.Which access modifier should class fields typically have to enforce encapsulation?

    • Aprivate
    • Bpublic
    • Cprotected
    • Ddefault
  3. 3.What is a getter method?

    • AA method that deletes a field value
    • BA constructor that initialises all fields
    • CA method that sets a new value on a field
    • DA public method that returns the value of a private field
  4. 4.What does this code print?

    class BankAccount {
        private double balance = 1000;
        public double getBalance() { return balance; }
        public void deposit(double amount) {
            if (amount > 0) balance += amount;
        }
    }
    public class Main {
        public static void main(String[] args) {
            BankAccount acc = new BankAccount();
            acc.deposit(-500);
            acc.deposit(200);
            System.out.println(acc.getBalance());
        }
    }
    • A500.0
    • B1000.0
    • C1200.0
    • D700.0
  5. 5.What is a setter method?

    • AA public method that validates and sets a private field value
    • BA method that reads a field value
    • CA method that creates a new instance
    • DA static factory method
  6. 6.What does this code demonstrate?

    class Person {
        private String name;
        private int age;
        public void setAge(int age) {
            if (age >= 0 && age <= 150) this.age = age;
            else throw new IllegalArgumentException("Invalid age: " + age);
        }
        public int getAge() { return age; }
    }
    • AEncapsulation with input validation
    • BInheritance
    • CMethod overloading
    • DPolymorphism
  7. 7.What is data hiding?

    • ARestricting direct access to an object's internal state using access modifiers
    • BEncrypting class fields
    • CDeleting unused variables
    • DUsing transient fields to exclude them from serialisation
  8. 8.What is an immutable class?

    • AA class with no constructors
    • BA class marked with the final keyword
    • CA class with only static fields
    • DA class whose objects cannot be modified after creation
  9. 9.Which of the following creates a properly immutable class?

    final class Point {
        private final int x;
        private final int y;
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int getX() { return x; }
        public int getY() { return y; }
    }
    • AImmutable — final class, private final fields, no setters
    • BNot immutable — fields should be public
    • CNot immutable — needs to extend Object explicitly
    • DNot immutable — needs setters
  10. 10.What is the JavaBeans convention for getters and setters?

    • AMethods named get<FieldName>() and set<FieldName>() with matching types
    • BAny public method accessing a field
    • CMethods named read() and write()
    • DMethods named fetch() and update()
  11. 11.What does this code print?

    class Counter {
        private int count = 0;
        public void increment() { count++; }
        public void reset() { count = 0; }
        public int getCount() { return count; }
    }
    public class Main {
        public static void main(String[] args) {
            Counter c = new Counter();
            c.increment();
            c.increment();
            c.increment();
            c.reset();
            c.increment();
            System.out.println(c.getCount());
        }
    }
    • A4
    • B3
    • C1
    • D0
  12. 12.Why is encapsulation important for maintenance?

    • AIt prevents the need for unit tests
    • BIt makes the code run faster
    • CIt reduces the number of classes needed
    • DIt allows the internal implementation to change without affecting external code
  13. 13.What is the difference between an immutable object and a final variable?

    • AThere is no difference
    • BA final variable cannot be reassigned, but the object it points to can still be mutated
    • CAn immutable object cannot be assigned to a final variable
    • Dfinal variables are only for primitives
  14. 14.What does this code print?

    import java.util.ArrayList;
    import java.util.List;
    class Bag {
        private List<String> items = new ArrayList<>();
        public void add(String item) { items.add(item); }
        public List<String> getItems() { return items; }
    }
    public class Main {
        public static void main(String[] args) {
            Bag b = new Bag();
            b.add("apple");
            List<String> list = b.getItems();
            list.add("banana");
            System.out.println(b.getItems().size());
        }
    }
    • A2
    • B0
    • CCompilation error
    • D1
  15. 15.How do you fix an encapsulation leak when returning a mutable collection?

    • AUse a static field instead
    • BMake the collection field public
    • CReturn a defensive copy or an unmodifiable view
    • DReturn the collection only from static methods
  16. 16.What is a Java Record (Java 16+) in the context of encapsulation?

    • AA replacement for interfaces
    • BA database record mapping class
    • CA concise immutable data class that auto-generates constructor, getters, equals, hashCode, and toString
    • DA mutable data container class
  17. 17.What does this code print?

    class Employee {
        private String name;
        private double salary;
        public Employee(String name, double salary) {
            this.name = name;
            setSalary(salary);
        }
        public void setSalary(double salary) {
            this.salary = salary < 0 ? 0 : salary;
        }
        public double getSalary() { return salary; }
    }
    public class Main {
        public static void main(String[] args) {
            Employee e = new Employee("Alice", -5000);
            System.out.println(e.getSalary());
        }
    }
    • ACompilation error
    • B0.0
    • C5000.0
    • D-5000.0
  18. 18.Which of the following violates encapsulation?

    • Apublic int age;
    • Bprivate int age; public void setAge(int a) { age = a; }
    • Cprivate int age; public int getAge() { return age; }
    • Dprivate final String id;
  19. 19.What is "tell, don't ask" in the context of encapsulation?

    • AAlways use getters instead of setters
    • BNever use getters — access fields directly
    • CUse verbose variable names
    • DTell an object what to do rather than asking for its data and doing the work externally
  20. 20.What is the benefit of encapsulation in multi-threaded programs?

    • AEncapsulation has no impact on thread safety
    • Bprivate fields are automatically synchronised
    • CIt automatically makes all methods thread-safe
    • DIt allows controlled synchronisation in one place rather than across all access points