Java Inner Class

Source: Internet
Author: User

Inner class is nested classes, also known as C + + and C # nested class. But the biggest difference between Java's inner class and C + + and C # is that a nested class contains a reference to its container class that can access the members of the container class. This is illustrated by the following code:

public class Container {



String Name;



Class Innerclass



{



Innerclass () {};



public void func ()



{



System.out.println (Name);



}



}



Public Container (String name) {

Name=name;



Innerclass a=new innerclass ();



}



public static void Main (String [] arg)



{



Container a=new Container ("Containera");



Innerclass b=a.new innerclass (); Note here



Innerclass c= (New Container ("Containerb")). New Innerclass (); Essentially equivalent to the previous sentence

A.func ();

C.func ();



}



}

Note that the unique new syntax, in which a static function creates a inner class, must have an instance of its container class. If you create directly



Innerclass b=new innerclass ();

Will cause a compilation error.

In the container constructor, this is automatically used as a reference to Innerclass when the Innerclass is created.

Use the members of the container class in inner class without specifying an instance and automatically point to the container class that created it.

This is a very useful grammatical feature and the compiler saves a lot of things for us.

The output of this example is:

Containera

Containerb



You can also see that Inner class can access any member of the container class, whether public, private, or protected members are all transparent. Otherwise, the container class can only access public members of the inner class.


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.