Introduction to Java within class

Source: Internet
Author: User

Member Inner classes in Java

The most common inner class is the member inner class, also known as the ordinary inner class. Let's look at the following code:

The result of the operation is:

As we can see from the code above, the use of the members ' inner classes is as follows:

1. The Inner class is defined inside the Outer class and is equivalent to the position of a member variable of the Outer class, and the Inner class can use any access control, such as public, protected, private, etc.

2. The test () method defined in the Inner class can directly access the data in the Outer class without being affected by the access control, such as direct access to private property A in the Outer class

3, after defining the member inner class, you must use the Outer class object to create the inner class object, but not directly to the new inner class object, namely: The Inner class object name = Outer class object. New inner class ();

4, after compiling the above program, you will find that two. class files have been generated

Where the second is the. class file for the outer class, the first is the. class file for the inner class, that is, the. class file for the member's inner class is always the case: the outer class name $ internal class name. class

In addition, friendly hints OH:

1. External classes cannot use the members and methods of the inner class directly.

You can first create an object of an inner class and then access its member variables and methods through the objects of the inner class.

2. If the external class and the inner class have the same member variable or method, the inner class accesses its own member variable or method by default, and if you want to access the member variable of the external class, you can use the This keyword. Such as:

Operation Result:

Introduction to Java within class

Related Article

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.