Anonymous class (anonymous class)

What is an anonymous class?

It is used when creating a class that is used only once on the spot.

Normally, you declare a class that implements an interface, create an instance of that class, and call a method, but with an anonymous class, you can declare the interface and use the method at the same time.

If you do not use anonymous classes

This time, I used a self-made interface with a method called output.

IPrint


public interface IPrint {
	void output();
}

Create a class that implements the IPrint interface and describe the processing details in the method.

PrintImpl


public class PrintImpl implements IPrint{

	@Override
	public void output() {
		System.out.println("aaa");
	}
}

Call it in the execution class.

Main


public class Main {

	public static void main(String[] args) {
		
		IPrint ip = new PrintImpl();
		ip.output();//On the console"aaa"Is output
	}
}

When using anonymous class

You can use IPrint methods in the execution class without creating a class that implements the interface.

Main


public class Main {

	public static void main(String[] args) {
		
		IPrint ip = new IPrint() {
			@Override
			public void output() {
				System.out.println("aaa");
			}
		};
		ip.output();
	}
}

In addition, you can reduce the number of lines with a lambda expression.

Main


public class Main {

	public static void main(String[] args) {
			
		IPrint ip = () -> System.out.println("xxxx");
		
		ip.output(); // "xxxx"Is output
	}
}

If you add a new method that is not in the interface, it will not be received as an interface type variable when the instance is created.

Main


public class Main3 {

	public static void main(String[] args) {
		
		new IPrint() {
			@Override
			public void output() {
				System.out.println("aaa");
			}
			
			public void output2() {
				System.out.println("bbb");
			}
		}.output2();
	}
}

Recommended Posts

Anonymous class (anonymous class)
Java anonymous class
11th class: Class
Class method
ObjectMapper class
ArrayList class
Anonymous class (aiming to introduce stream api)
11th class: Class
Anonymous class (anonymous class)
Class method
ObjectMapper class
ArrayList class
Java Callback Simple Sample Part2 Anonymous Class Example
Java class methods
Class and model
[Java] Class inheritance
9th class: assert_equal
Java HashMap class
10th class: Recursion
About class inheritance.
java (abstract class)
Class in Ruby
[Java] Nested class
About Java class
8th class: rake
Speaking of which, an anonymous class has appeared.
String class methods
[Week 11] class, ruby_sixth
java.lang.IncompatibleClassChangeError: Implementing class
[java] abstract class
[Java] Object class
Java local class
5th class: Output
Impl class Vo class
WildFly class loading