Home  >  Article  >  Java  >  Talk about Java’s anonymous inner classes

Talk about Java’s anonymous inner classes

高洛峰
高洛峰Original
2016-12-15 12:48:421173browse

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 CONSTANT =   
    new HashMap();  
static {  
    CONSTANT.put("1", "one");  
    CONSTANT.put("2", "two");  
}

In fact, you can also write it like this:

Java code

private final static Map CONSTANT =   
     new HashMap() {  
    {  
        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 CONSTANT = new HashMap() {  
    {  
        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 list = new ArrayList() {  
    public boolean add(String e) {  
        System.out.println("Cannot add anything!");  
    }  
      
    //代码块的顺序在前后都无所谓,可以出现在类范围的任何位置。  
    {  
        add("Boyce Zhang");  
    }  
};  
  
//局部代码块调用父类方法。  
dao.add(new User(){  
    {  
        setName("Boyce Zhang");  
        setAge(26);  
    }  
});  
  
//重写父类方法  
ThreadLocal threadLocal = new ThreadLocal() {  
    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 map = new HashMap();  
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