search
HomeJavajavaTutorialTalk about Java's anonymous inner classes

Talk about Java's anonymous inner classes

Dec 15, 2016 pm 12:48 PM
anonymous inner class

In many cases, we need to initialize a static Map or List inside the class, and then save the constant value for use by the internal methods of the class.
Our usual approach is:
First initialize a static variable of Map.
Then add the constant value in the static block:

Java code

private final static Map<String, String> CONSTANT =   
    new HashMap<String, String>();  
static {  
    CONSTANT.put("1", "one");  
    CONSTANT.put("2", "two");  
}

In fact, you can also write it like this:

Java code

private final static Map<String, String> CONSTANT =   
     new HashMap<String, String>() {  
    {  
        put("1", "one");  
        put("2", "two");  
    }  
};

If you are unfamiliar with this method, then look at a familiar one first:

Java Code

new Thread() {  
    public void run() {  
        System.out.println("Thread running!");  
    };  
}.start();

In fact, the above code means to declare a subclass of Thread and override the run() method of Thread, then create an instance of the subclass and call its start() method. Since the declared subclass of Thread has no name, it is called an anonymous class. And because a class without a name can only exist inside a class or a method, it is also called an anonymous inner class.

The syntax of anonymous inner classes can also be written like this:

Java code

Thread thread = new Thread() {  
    public void run() {  
        System.out.println("Thread running!");  
    };  
};   
thread.start();

The only difference is that instead of directly creating a subclass and calling its method, you declare a parent class reference thread of the subclass, and then pass it through The parent class reference calls the child class method.
After creating an instance of an anonymous class, start() is not executed immediately, and the methods for creating an instance and executing the instance are separated.

The difference between the two is equivalent to:

Java code

//1  
new User().setName("Boyce Zhang");  
  
//2  
User user = new User();  
user.setName("Boyce Zhang");

Another syntax scenario of anonymous inner classes:

Java code

new Thread() {  
    public void run() {  
        System.out.println("Thread running!");  
    };  
    {  
        start();  
    }  
};

In fact, this way of writing is in the class local code block of the anonymous subclass Call its class method.
Statements within a local code block are implicitly executed by the class loader immediately after an instance of the class is created.
Equivalent to:

Java code

public class MyThread extends Thread {  
    {  
        start();  
    }  
    public void run() {  
        System.out.println("Thread running!");  
    };  
}

So apart from the slight difference in execution time between the three methods, there is not much difference in the effect.

In this way, the previous method of initializing Map is not difficult to understand:

Java code

private final static Map<String, String> CONSTANT = new HashMap<String, String>() {  
    {  
        put("1", "one");  
        put("2", "two");  
    }  
};

The principle is:
Declare and instantiate a subclass of HashMap (the subclass does not override any method of the parent class HashMap ), and call the put() method of the parent class HashMap in the class local code block of the subclass.
Finally declare a Map interface reference CONSTANT pointing to an instance of the instantiated HashMap subclass.
According to the previous example, we know that the put() method call in the class local code block will be implicitly executed by the class loader after the anonymous subclass of HashMap is instantiated.

In fact, for any class or interface in Java, you can declare an anonymous class to inherit or implement it. Such as:

Java code

//重写父类方法,局部代码块调用自己重写过的父类方法。  
List<String> list = new ArrayList<String>() {  
    public boolean add(String e) {  
        System.out.println("Cannot add anything!");  
    }  
      
    //代码块的顺序在前后都无所谓,可以出现在类范围的任何位置。  
    {  
        add("Boyce Zhang");  
    }  
};  
  
//局部代码块调用父类方法。  
dao.add(new User(){  
    {  
        setName("Boyce Zhang");  
        setAge(26);  
    }  
});  
  
//重写父类方法  
ThreadLocal<User> threadLocal = new ThreadLocal<User>() {  
    protected String initialValue() {  
        return new User("Boyce Zhang", 26);  
    }  
};

Inside the anonymous class, we can not only implement or override the methods of its parent class.
And you can also execute your own methods or the methods of its parent class in the local code block of its class.
This is not a special syntax for anonymous inner classes, but a Java syntax that applies to any class.

This way of writing is often used to execute certain methods immediately after instantiating a class to initialize the data of some class instances.
Its function is the same as instantiating a class first, and then using its reference to call the method that needs to be called immediately, such as:

Java code

Map<String, String> map = new HashMap<String, String>();  
map.put("1", "one");  
map.put("2", "two");

The advantage of this syntax is that it is simple, do something immediately after instantiating a class Things are more convenient.
The effect is a bit like the instant function in Javascript. But there is an essential difference.
Because Javascript does not have the concept of a class, or in other words, a function in Javascript is a class, and a class is a function, so the instant function executes the entire function after loading. Java's local code block can choose to execute any method of the class.

Of course, this way of writing also has its shortcomings:
Each instance of an inner class will implicitly hold a reference to the outer class (except static inner classes). On the one hand, this is a waste of redundant references, and on the other hand, it is used as a string. When serializing this subclass instance, the external class will also be serialized unknowingly. If the external class does not implement the serialize interface, an error will be reported.


For more articles related to Java’s anonymous inner classes, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor