Junior — Middle
What is the role and usage of anonymous objects in programming?
sobes.tech AI
Answer from AI
Anonymous objects in programming are objects that are created without being assigned to a variable. They are often used when the object is needed only once, for example, to pass a parameter or call a method.
In Android and Java, this is commonly seen when creating listeners or callbacks:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// handle click
}
});
Here, an anonymous object of the class View.OnClickListener is created without a separate name. This is convenient when the class is used only in one place and does not require reuse.
Advantages:
- Reduces code length
- Localizes logic
- Convenient for implementing interfaces with a single method (especially with lambdas)
Disadvantages:
- Can complicate code readability when large in volume
- Harder to reuse
In modern versions of Java and Kotlin, lambda expressions are often used instead of anonymous classes for conciseness.