The inner class in JAVA-anonymous inner class

Anonymous inner class is also an inner class without a name (mostly used to focus on the implementation and not the name of the implementation class). Because there is no name, the anonymous inner class can only be used once. It is usually used to simplify code writing, usually in conjunction with the interface use.

But there is another prerequisite for using anonymous inner classes: you must inherit a parent class or implement an interface .
    When an anonymous inner class is created, an instance of this class will be created immediately, the class definition disappears immediately, and the anonymous inner class cannot be reused.
    The format for defining anonymous inner classes is as follows:
new 父类名(参数列表)|实现接口名()  
{  
 //匿名内部类的类体部分  
};
The most common way to create an anonymous inner class is to create an object of a certain interface type, as shown in the following program:
interface Animal {
    public void eat();
}
 
public class Demo {
    public static void main(String[] args) {
    	//实现方式1
    	Animal Dog = new Animal() {
            public void eat() {
                System.out.println("Dog eat something");
            }
        };
        Dog.eat();
        
    //实现方式2
        new Animal(){
        	public void eat(){
        		System.out.println("Dog eat something");
        	}
        }.eat();
    
    }
}
As you can see, we directly implement the methods in the abstract class Person in braces, so that we can omit the writing of a class.
As can be seen from the above example, as long as a class is abstract or an interface, the methods in its subclasses can be implemented using anonymous inner classes

In addition, there is a common situation in the realization of multi-threading, because to achieve multi-threading must inherit the Thread class or inherit the Runnable interface

Example 1
//Thread类的匿名内部类实现
public class Demo {
    public static void main(String[] args) {
        Thread t = new Thread() {
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.print(i + " ");
                }
            }
        };
        t.start();
    }
}

Example 2
//Runnable接口的匿名内部类实现
public class Demo {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.print(i + " ");
                }
            }
        };
        Thread t = new Thread(r);
        t.start();
    }
}

Operation result: 1 2 3 4 5



Guess you like

Origin blog.csdn.net/liushulin183/article/details/46700465