Java anonymous inner class detailed

Syntactic structure of anonymous inner classes

Anonymous inner classes are mainly for abstract classes and interfaces that cannot directly create objects

new 类名或接口名(){
    重写方法;
};

Examples

public interface Body extends Mammal
{
	class Heart
	{
		public void work()
		{
			System.out.println("is beating");
		}
	}
	
	class A{
		
	}
	Object o = new Object() {
		
	};
	Object object = new Object() {
		
	};
	static Mammal mammal = new Mammal() {
		public void move() {
			System.out.println("moving by fins");
		}
	};

	public static void main(String[] args) {
		mammal.move();
		
		new Mammal() {
			public void move() {
				System.out.println("moving by fins");
			}		
		}.move();	
		
		new Mammal() {
			public void move() {
				System.out.println("moving by fins");
			}
			public void eat() {
				System.out.println("eating by mouth");
			}		
		}.eat();
	}
}

The anonymous class expression contains the following internal parts:

  • Operator
  • An interface to be implemented or a class to be inherited
  • A pair of brackets
  • A paragraph is enclosed in "{}" class declaration body
  • ";" At the end
Published 19 original articles · praised 0 · visits 1616

Guess you like

Origin blog.csdn.net/FOREVER_GWC/article/details/105243881