Java Anonymous Inner class example

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.