Junior — Middle
How can external code modify the state of a class?
sobes.tech AI
Answer from AI
External code can modify the state of a class in several ways:
- Through public methods (setters) — the class provides methods to change its fields, for example
setName(String name). - Through public fields — if the class fields are declared as
public, external code can modify them directly (not recommended due to violation of encapsulation). - Using design patterns — for example, through the Builder pattern or methods that return mutable objects.
Example in Kotlin (Android):
class User {
var name: String = ""
private set // restricts external direct modification
fun updateName(newName: String) {
name = newName
}
}
val user = User()
user.updateName("Ivan") // changing state via method
Thus, the best approach is to provide controlled access to modify the state through class methods, maintaining encapsulation.