Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Anonymous Class

Java Anonymous Class

Java Objects and Classes Java Objects and Classes

In Java, you can implement a class that contains another class and instantiate it directly without providing any class name.

This is mainly used to create an object to perform a specific task when needed, which can make the code more concise.

An anonymous class is a class that cannot have a name; it cannot be referenced and can only be used when created with new a statement to declare them.

Anonymous class syntax format:

class outerClass {

    // Define an anonymous class
    object1 = new Type(parameterList) {
         // Anonymous class code
    };
}

The code above creates an anonymous class object object1. Since an anonymous class is defined in expression form, it ends with a semicolon ; at the end.

An anonymous class usually extends a parent class or implements an interface.

Anonymous class extending a parent class

In the following example, a Polygon class is created with only one method display(), and the AnonymousDemo class extends the Polygon class and overrides its display() method:

Example

class

Polygon

{

   

public

void

display

(

)

{

     

System

.

out

.

println

(

Inside the Polygon class

)

;

   

}

}

class

AnonymousDemo

{

   

public

void

createClass

(

)

{

     

// The created anonymous class extends the Polygon class

     

Polygon

p1

=

new

Polygon

(

)

{

         

public

void

display

(

)

{

           

System

.

out

.

println

(

Inside the anonymous class.

)

;

         

}

     

}

;

      p1.

display

(

)

;

   

}

}

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       AnonymousDemo an

=

new

AnonymousDemo

(

)

;

       an.

createClass

(

)

;

   

}

}

After executing the above code, an object p1 of the anonymous class will be created; this object will call the anonymous class's display() method, and the output will be:

在匿名类内部。

Anonymous class implementing an interface

The anonymous class created in the following example implements the Polygon interface:

Example

interface

Polygon

{

   

public

void

display

(

)

;

}

class

AnonymousDemo

{

   

public

void

createClass

(

)

{

     

// Anonymous class implements an interface

     

Polygon

p1

=

new

Polygon

(

)

{

         

public

void

display

(

)

{

           

System

.

out

.

println

(

Inside the anonymous class.

)

;

         

}

     

}

;

      p1.

display

(

)

;

   

}

}

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

      AnonymousDemo an

=

new

AnonymousDemo

(

)

;

      an.

createClass

(

)

;

   

}

}

The output is:


在匿名类内部。

Java Objects and Classes Java Objects and Classes