Java nested class (translated from Java tutorials)

Source: Internet
Author: User

From http://www.cnblogs.com/ggjucheng/archive/2012/12/01/2797685.html

English from http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

JavaProgramThe language allows you to declare another class in one class. Such classes become Nested classes, which are described as follows:

 
ClassOuterclass {...ClassNestedclass {...}}

Term: There are two types of nesting: static or non-static. The declared static nesting class is called static nesting class. Non-static Nested classes are called internal classes.

 
ClassOuterclass {...Static ClassStaticnestedclass {...}ClassInnerclass {...}}

A nested class is a member of its encapsulation class. A non-static nested class can access other members of its encapsulation class, even if these member declarations are private. The static nested class cannot access other members of the encapsulated class. Just like a member of an external class, the nested class can be declared as private, public, protected, and private in the package (review the external class can only be declared as public or private in the package)

 

Why use Nested classes

There are several compelling reasons for using nested classes:

    • It is a logical grouping method that uses classes in one place.
    • It enhances Encapsulation
    • Nested classes can improve readability and maintainability.Code.

Logical grouping of classes-if a class is only used by another class, it is logical to nest it into the class so that the two classes can be together. Nested helper classes can simplify the package.

Enhanced encapsulation-consider two top-level classes, A and B. If B needs to access the private member of a and hide Class B in Class A, even if the member declaration of Class A is private, B can also access them. More importantly, the bitself can also be hidden from the outside.

Code with better readability and maintainability-nesting small classes in top-level classes makes the code closer to use.

 

 

Static nesting class

Like class methods and class variables, a static nested class is associated with its external class. Just like static class methods, a static nested class cannot directly reference the instance variables or methods of the encapsulated class-it can only access them through the reference of the encapsulated class.

Note: A static nested class accesses the instance members of its encapsulation class (and other classes), just like accessing other top-level classes. In fact, a static nested class is like a top-level class, but its behavior is nested in another top-level class to facilitate packaging.

Static Nested classes are accessed using the name of the encapsulated class:

 
Outerclass. staticnestedclass

For example, to create a static nested class object, the syntax is:

 
Outerclass. staticnestedclass nestedobject =NewOuterclass. staticnestedclass ();

 

Internal class

Like the instance method and instance field, an internal class is associated with the encapsulated class instance and can directly access the members and methods of this object. Because an internal class is associated with an instance, it cannot define any static members.

The object instance of the internal class exists in the instance of the external class. Consider the following class:

 
ClassOuterclass {...ClassInnerclass {...}}

An internal class instance can exist in an external class instance and can directly access the methods and fields of the encapsulated instance. Illustrate this idea:

 

 

An internal class instance exists in an external class instance.

Before instantiating an internal class, you must first instantiate an external class. Then, an internal class object is created based on an external class object. The syntax is:

In addition, there are two special internal classes: local class and Anonymous class (which can also be an anonymous internal class ). The two will be discussed later.

 

Internal Class Example

To demonstrate the use of internal classes, let's think about an array. In the following example, an array is created and filled with integers. The index values of the output array are in ascending order.

The following Datastructure classes include:

    • Datastructure external class, contains the method to add an integer to an internal array, and outputs the index value in the array
    • InnereveniteratorInternal class, similar to java standard iterator. The iterator is used to traverse a data result. It is typically used to determine whether the last element is reached, retrieve the current element, and move it to the next element.
    • Instantiate in the main methodDatastructure object, which is used to fill the ArrayArrayofints is a series of Integers (0, 1, 2, 3, etc.), and then callsPrintevenMethod, outputArrayofints.
 Public   Class  Datastructure { //  Create an array      Private   Final   Static   Int Size = 15 ;  Private   Int [] Arrayofints = New   Int  [Size];  Public  Datastructure (){  // Fill the array with ascending integer values          For ( Int I = 0; I <size; I ++ ) {Arrayofints [I] = I ;}}  Public   Void  Printeven (){  //  Print out values of even indices of the array Innereveniterator iterator = This . New Innereveniterator ();  While  (Iterator. hasnext () {system. Out. println (iterator. getnext () + "" );}}  //  Inner class implements the iterator Pattern      Private   Class  Innereveniterator {  //  Start stepping through the array from the beginning          Private   Int Next = 0;  Public   Boolean  Hasnext (){  //  Check if a current element is the last in the array              Return (Next <= size-1 );}  Public   Int  Getnext (){  //  Record a value of an even index of the array              Int Retvalue =Arrayofints [next];  //  Get the next even element Next + = 2 ;  Return  Retvalue ;}}  Public   Static   Void  Main (string s []) {  //  Fill the array with integer values and print out only  //  Values of even indices Datastructure DS = New  Datastructure (); DS. printeven ();}} 

The output is:

 
0 2 4 6 8 10 12 14

Note:Innereveniterator is a direct referenceInstance variables of the Datastructure objectArrayofints.

Internal classes can be used to implement helper classes, just like the example above. If you plan to process user interface events, you need to guide how to use internal classes because internal classes are widely used in the event processing mechanism.

 

Local and anonymous internal classes

There are two benign internal classes. You can declare an internal class in the method body. This class becomes a local internal class. You can also declare an internal class without a name in the method body. This class is an anonymous internal class. We will encounter it in Java advanced programming.

 

Modifier

You can use modifiers for internal classes, just like external class members. For example, you can use special access-private, public, and protected-to restrict access to internal classes, just like other class members.

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.