Understanding anonymous internal classes in five minutes-Java study notes

Anonymous inner class:
Essence: The essence of an anonymous inner class is an object that inherits an anonymous subclass of the parent class (a subclass object of a class).
Role: Simplify the code

格式:
	new 类名/接口名(){
	    重写抽象方法
	}

Now we have a Person class.

class abstract Person {
       public abstract void eat();

}

Requirement: execute the eat method of the Person class.
Steps:
1. Create a subclass to inherit from the Person class
2. Override the eat method in the subclass
3. Create a subclass object
4. Use the subclass object to call the eat method

//创建一个子类继承Person类
class Student extends Person {
	//重写方法
	@Override
	public void eat() {
    	   System.out.println("学生吃学生餐");
	}
}
//创建一个测试类
public class Test {
	public static void main(String[] args) {
		//创建子类对象
		Person student = new Student;
		//调用eat方法
		student.eat();
	}
}

I'm such a lazy person, I write too much code like this, and I don't have the energy to continue typing.
Is there an easier way?
Now look at the first three steps of the operation, our purpose is to create a subclass object.
The essence of an anonymous inner class is a subclass object of a class.
Can the first three steps be condensed into one step? Just use anonymous inner classes!
I'm such a genius~

//创建一个测试类
public class Test {
	public static void main(String[] args) {
		//创建Person的匿名内部类对象
		Person student = new Person{
		  @Override
		  public void eat() {
    	            System.out.println("学生吃学生餐");
	         }
		};//这里的分号不要忘记咯。
		//调用eat方法
		student.eat();
	}
}

To summarize:
Anonymity just hides the name. In the case, it hides the name of the Student class.
What Student did, overriding the eat method, was also done in the anonymous inner class.
Therefore, when we want to get a subclass object of a class, we can directly create an anonymous inner class of this object.
Similarly, the interface is the same method.

Guess you like

Origin blog.csdn.net/LinKin_Sheep/article/details/109313760