public class Test {
public static void Main (string[] args) {
4. Anonymous inner class
is primarily for those abstract classes and interfaces that cannot directly create objects.
Student stu=new Student ();
System.out.println (Stu.getclass ());//class com.aowin.noname.Student
4.1. Creating an anonymous inner class object from an entity class
Equivalent to creating a subclass object of the class
Person P=new person () {
public void Eat () {
System.out.println ("Eat eight RMB package");
}
};
P.eat ();
System.out.println (P.getclass ());//class com.aowin.noname.test$1//system automatically names the subclass Test$1
Dog Dog=new Dog ();
Dog.bark ();
4.2. Creating an anonymous inner class object from an abstract class
Corresponds to a subclass object that defines the abstract class and overrides all abstract methods in the abstract class
Animal an=new Animal () {
public void bark () {
System.out.println ("Wang Woo ...");
}
};
An.bark ();
The package name plus class name is returned
System.out.println (An.getclass ());//class com.aowin.noname.test$2
4.3. Creating an anonymous inner class object from an interface
Equivalent to an implementation class object that defines the interface and overrides all the abstract methods in the interface
Sportable s=new sportable () {
public void Sport () {
System.out.println ("playing basketball");
}
};
S.sport ();
System.out.println (S.getclass ());//class com.aowin.noname.test$3
}
}
Entity class
Class person{
public void Eat () {
System.out.println ("eat");
}
}
Class Student extends person{
public void Eat () {
System.out.println ("Eat eight RMB package");
}
}
Abstract class
Abstract class animal{
public abstract void bark ();
}
Class Dog extends animal{
public void bark () {
System.out.println ("barking ...");
}
}
Interface
Interface sportable{
public abstract void sport ();
}
Java Anonymous Inner class example