Sobes.tech
Junior

What is an anonymous class?

sobes.tech AI

Answer from AI

An anonymous class is a local class without a name. It is declared and instantiated (an object is created) in a single expression. It is used to create objects that will be used only once, for example, to implement an interface or extend an existing class "on the fly".

Main characteristics:

  • No explicit name.
  • Cannot have constructors (but can have instance initializers and static initializers).
  • Cannot be abstract, static, or public.
  • Has access to final or effectively final local variables from the outer context.

Example of using it to implement the Runnable interface:

new Runnable() {
    @Override
    public void run() {
        // Code to be executed
    }
};

Example of extending the Button class:

new Button(context) {
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Touch event handling
        return super.onTouchEvent(event);
    }
};

Advantages:

  • Lambda expressions (in Java 8+) are often a more concise alternative for simple cases.
What is an anonymous class? — Android - sobes.tech