Internal Study Notes (3) Anonymous internal class

Source: Internet
Author: User
I will write this article by myself, because anonymous internal classes are the most difficult to understand in the internal class series.

A. inherited anonymous internal class.

Reference reprinted code:

The result is output: driving another car! The car reference variable is not a reference car object, but an object of the car anonymous subclass.
The key to building an anonymous internal class is to override one or more methods of the parent class. It is emphasized that the method of rewriting the parent class, rather than creating a new method. Because it is impossible to call methods that the parent class does not have by referencing the parent class! Creating a new method is unnecessary. In short, refer to polymorphism.

You may be confused here, especially

Car car = new car () {public void drive () {system. Out. println ("driving another car! ");}};

Let me explain this code: It is equivalent

Their difference is that the xxx name is not needed here.

B. Anonymous internal classes of abstract classes and interfaces.

The above is an abstract class code, the interface is almost identical with the abstract class, just change abstract to interface.

C. Parameter-Based Anonymous internal class

Reference reprinted code:


If you can understand both A and B, you don't need to explain it here.

Summary: The core of anonymous internal classes is "inheritance" and "Implementation". Because internal classes do not have constructor methods, the initialization of internal classes is only "code block ".
You just need to think about how the abstract class and interface will be new out of the instance? Must be their subclass.




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.