-~~ Also called an inner class or ~~ an anonymous class. As the name implies, it's an unnamed class. --Unlike a normal class, describe the constructor and the processing part at the same time.
Sample1.java
//Interface used in anonymous classes
interface I_Hello {
public void print();
}
//Calling class
public class Sample {
public static void main(String[] args) {
I_Hello p = new I_Hello() {
@Override
public void print() {
System.out.println("Hello World");
}
};
p.print();
}
}
--Result of execution of anonymous class
Hello World
Sample2.java
//interface
interface I_Hello {
public void print();
}
class Hello implements I_Hello {
@Override public void print(){
System.out.println("Hello World");
}
}
//Calling class
public class Sample2 {
public static void main(String[] args) {
I_Hello p = new Hello();
p.print();
}
}
Hello World
――As you can see in the sample above, if you do not use an anonymous class, you have to prepare a class Hello that materializes the interface, so it is a large scale compared to an anonymous class. --In the case of anonymous class, it can be described simply.
Recommended Posts