• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Inheritance » Anonymous Inner Class in Java with Example
Next →
← Prev

Anonymous Inner Class in Java with Example

By Dinesh Thakur

Sometimes you need a pure class, and to be instantiated only once in your code. When this is the case, you can use an anonymous inner class. It is called an inner class because it defined inside another class.

Anonymous inner class are the local inner classes that declared without a name, but an object of this class can be created. All of the code for the anonymous class is coded within the method where we need to create an instance of the anonymous class. Since anonymous inner classes do not have a name so you cannot use the new keyword in the usual way to create an instance of the class. Anonymous inner classes are declared and instantiated at the same time.

Anonymous inner classes can also be used to provide a similar facility as that provided by inner classes. Although anonymous inner classes result in more compact programs but they do make the code more difficult to read.

We’ll be covering the following topics in this tutorial:

  • Anonymous Inner Class Properties 
  • There are three types of anonymous inner class
  • Difference between Anonymous class and Anonymous Inner class:

Anonymous Inner Class Properties 

Anonymous inner classes defined within methods rather than being members of an outer class. They are local to the methods, and you cannot mark them with any access modifier, like static, public, or private, like local method variables.

Anonymous inner classes always have to either implement interfaces or extend superclasses. You do not need to use the keywords implement or extends when you declare it. The anonymous inner class has to implement every abstract method in the interface or superclass. 

Anonymous inner classes always use the no-arg, default constructor out of their superclasses to create instances. If the anonymous inner class used for the implementation of interfaces, they use java.lang.object(). 

Anonymous inner cases are compiled into classes called OuterClass-  Namre$n.class – n is the running number of the inner classes inside the outer classes. 

The advantage of using anonymous inner class fro event handling is that you can avoid large if-else statements to decide which component is being handled. Each component gets its own event handler so each event handler knows implicitly the component for which it is working.

We use the following syntax to construct instances of anonymous inner classes:  
new SuperClassName/InterfaceName() {  
// extends superclass or implements  interface                                        
// invoke the default no-arg constructor or Object[]    
// Implement abstract methods in superclass/interface    
// More methods if necessary……  
}   

The new operator followed by the name of an existing class or interface, followed by a set of parentheses. Next, you write the body of the class, enclosed in curly braces. The expression
creates an object that is an instance of a class that either extends the specified superclass or implements the specified interface. A reference to the object returned. (Notice that you do not use the extends or implements keywords in the expression.)

The instance that has been created may be used as a method argument or assigned to a variable.

Java Anonymous Class Example

java anonymous class

class outer 
{
      private double i = 11.5 ;
      private static String str = "Hi Java World";
      public void display()
      {
           // Anonymous class
           Object Obj=new Object()
          {
             public String toString()
                                   { return("Anonymous Class");}
           };
        
           System.out.println("i = " + i);
           System.out.println("str = " + str);
           System.out.println(Obj.toString());
        }
}
class AnonymousClass
{
     public static void main(String[] arga)
     {
      outer outobj = new outer(); //create instance of outer class
      outobj.display();
     }
 }

Anonymous Inner Classes in Java Example

Explanation: When this program compiled, there classes AnonymousClass.class, Outer.class and Outer$1.class are created. These numbers incremented for each anonymous class created by the compiler.
In this program,
new Object() {}
Declares and instantiates an anonymous class. The new keyword followed by the name of the class that specifies the type of object created from an anonymous class. It is followed by empty parentheses, which indicates no argument passed to the constructor of an anonymous class. The code of the class then follows it. An assignment statement can use an anonymous class as shown in the example. In that case, an anonymous class body is followed by a semicolon that marks the end of the assignment statement. The semicolon is part of an assignment statement, not the anonymous class. The following points should be kept in mind while working with anonymous inner classes.

The following points should be kept in mind while working with anonymous inner classes.
• Anonymous inner class cannot have explicit constructors because they have no name to give to the constructor.
• It cannot be public, protected, private or static.
• It cannot either extend a class or implement an interface.
• The anonymous inner class type must be either a subclass of the named type or implementation of the named interface.
• It cannot access static fields, methods or classes (with an exception that constant fields can be declared both static and final).
• It should use when only one instance of the class is needed, and the body of the class is concise.

• It is not a member of any enclosing classes. Rather than being declared along with other members, it is both declared and instantiated where an expression is legal, they must be kept short or fewer or readability will suffer.

• An anonymous class instance is occur in a non-static context.

• You can declare an anonymous class to implement only one interfaces at a time.

• The Clients of an anonymous class invoke only members that it inherits from its super class.

• An anonymous inner class must implement an interface or extend a superclass, but it cannot have an explicit extends or implements clause.

• An anonymous class must always implement all the abstract methods in the superclass or in the interface.

There are three types of anonymous inner class

• Anonymous inner class that extends Class.
• Anonymous inner class that implements interface.
• Anonymous inner class that defined inside method argument.

Difference between Anonymous class and Anonymous Inner class:

• In java, the typical class can extend a class and implement any number of interface simultaneously.
• In java, standard class, we can write any number of constructors.

Anonymous Classes

• In Java, we all encounter situations where we need to create an object but does not need to bother giving it an explicit name.
• With the inner classes, you can create and instantiate a class without bothering to give it a name. It is called an anonymous class.
• This unnamed get rid of additional named objects and makes the code more readable.

Anonymous Inner Classes:

• Anonymous inner classes don’t have a name, and their type must be either a extend another class or implement an interface.
• An anonymous inner class always created as part of a statement; don’t forget to enclose the statement with a curly brace.
• Anonymous inner class are the local inner classes that declared, defined, and automatically instantiated as part of a method invocation.
• In anonymous Inner class, we can’t write any constructor.

You’ll also like:

  1. Anonymous Inner Classes in Java with Examples
  2. What is anonymous FTP?
  3. Inner class in java with Example
  4. Object Class in Java Example
  5. Regular Inner Class Example in Java
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW