Home > Java > javaTutorial > body text

Talk about Java's anonymous inner classes

高洛峰
Release: 2016-12-15 12:48:42
Original
1262 people have browsed it

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");  
}
Copy after login

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");  
    }  
};
Copy after login

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();
Copy after login

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();
Copy after login

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");
Copy after login

Another syntax scenario of anonymous inner classes:

Java code

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

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!");  
    };  
}
Copy after login

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");  
    }  
};
Copy after login

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);  
    }  
};
Copy after login

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");
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!