What is encapsulation in Java?
A
Combining classes into packages
B
Hiding internal details and showing only functionality
C
Inheriting methods from another class
D
Writing methods inside interfaces
Analysis & Theory
Encapsulation hides the internal state of an object and requires interaction through public methods.
Which access modifier is commonly used for encapsulated class fields?
Analysis & Theory
`private` ensures data hiding, making fields accessible only within the class.
What is the purpose of getter methods?
A
To modify private fields
B
To return the value of private fields
Analysis & Theory
Getter methods are used to access private field values from outside the class.
Which of the following is NOT a benefit of encapsulation?
B
Protects data integrity
C
Allows direct access to fields
D
Simplifies code maintenance
Analysis & Theory
Encapsulation prevents direct access to fields; it uses methods for controlled access.
What is the output?
```java
class Person {
private String name = "Alice";
public String getName() {
return name;
}
}
class Main {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.getName());
}
}```
Analysis & Theory
`getName()` returns the private `name` field, which is 'Alice'.
Which of the following best demonstrates encapsulation?
A
Using only public fields
B
Using private fields with public getters/setters
C
Making all methods static
Analysis & Theory
Private fields with public getter and setter methods encapsulate and protect data.
What is the output?
```java
class Box {
private int size;
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}
class Main {
public static void main(String[] args) {
Box b = new Box();
b.setSize(25);
System.out.println(b.getSize());
}
}```
Analysis & Theory
`setSize()` assigns value to `size`, and `getSize()` returns 25.
Can you access private fields directly from outside the class?
B
Only if the field is static
C
Only inside static blocks
D
No, you must use methods like getters/setters
Analysis & Theory
Private fields are only accessible inside their class; use methods for access.
Which statement is true about encapsulated classes?
A
They expose all data directly
B
They can only use static methods
C
They use methods to access and update fields
D
They cannot have constructors
Analysis & Theory
Encapsulated classes use methods to access and modify data, ensuring control and validation.
Why are setters useful in encapsulation?
A
They protect the method from being called
B
They allow data to be updated with validation
C
They remove the need for constructors
D
They make fields public
Analysis & Theory
Setters enable controlled modification of private data, often with validation logic.