🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #78

Java Anonymous


Anonymous Class

An anonymous class is a class without a name. It is created and used at the same time.

You often use anonymous classes to override methods of an existing class or interface, without writing a separate class file.

Here, we create an anonymous class that extends another class and overrides its method:

// Normal class
class Animal {
  public void makeSound() {
    System.out.println("Animal sound");
  }
}

public class Main {
  public static void main(String[] args) {
    // Anonymous class that overrides makeSound()
    Animal myAnimal = new Animal() {
      public void makeSound() {
        System.out.println("Woof woof");
      }
    }; // semicolon is required to end the line of code that creates the object

    myAnimal.makeSound();
  }
}

Anonymous Class from an Interface

You can also use an anonymous class to implement an interface on the fly:

// Interface
interface Greeting {
  void sayHello();
}

public class Main {
  public static void main(String[] args) {
    // Anonymous class that implements Greeting
    Greeting greet = new Greeting() {
      public void sayHello() {
        System.out.println("Hello, World!");
      }
    };

    greet.sayHello();
  }
}

Note: When to Use Anonymous Classes? Use anonymous classes when you need to create a short class for one-time use. For example: Overriding a method without creating a new subclass Implementing an interface quickly Passing small pieces of behavior as objects

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Java Anonymous – FAQs

Quick answers about learning Java Anonymous in Java.

This free note from CodingNow 2.0 explains Java Anonymous in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Java Anonymous, is 100% free with no signup required.
With focused practice, most students grasp Java Anonymous in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now