Java deeply understands Nested classes and internal classes

Source: Internet
Author: User

1. What are nested and internal classes?
You can define another class within a class. This class is called the nested classes. It has two types:
Static and non-static nesting classes. Static Nested classes are rarely used. The most important is non-static Nested classes, which are called
Internal class (inner ). Nested classes are introduced from JDK1.1. The inner class can be divided into three types:
1. Internal classes directly defined in a class (external class;
2. Internal classes defined in a method (external class method;
Third, anonymous internal class.
The following describes the usage and precautions of these Nested classes.
Ii. Static nesting
The following code defines a static nested class,
Public class StaticTest {
Private static String name = "javaJohn ";
Private String id = "X001 ";
Static class Person {
Private String address = "swjtu, chenDu, China ";
Public String mail = ""; // internal class public Member
Public void display (){
// System. out. println (id); // you cannot directly access non-static members of an external class.
System. out. println (name); // only the static members of the external class can be accessed directly.
System. out. println ("Inner" + address); // access the internal class member.
Public void printInfo (){
Person person = new Person ();
Person. display ();
// System. out. println (mail); // inaccessible
// System. out. println (address); // inaccessible
System. out. println (person. address); // you can access private members of an internal class.
System. out. println (person. mail); // you can access public members of the internal class.
Public static void main (String [] args ){
StaticTest staticTest = new StaticTest ();
StaticTest. printInfo ();
In a static nested class, you cannot access non-static members of the external class, which is limited by "static methods cannot access non-static members directly" in Java syntax.
To access external class variables, you must use other methods. For this reason, static Nested classes are rarely used. Note:
Some members of the department class are special and cannot be accessed directly, but they can be accessed through internal classes. This is because all the Members and methods in the static nest think
Static. Note that the internal static class Person is only visible within the StaticTest class. If it is referenced or initialized in other classes, it is incorrect.
3. Define internal classes in external classes
The following code defines two internal classes and their call relationships for external classes:
Public class Outer {
Int outer_x = 100;
Class Inner {
Public int y = 10;
Private int z = 9;
Int m = 5;
Public void display (){
System. out. println ("display outer_x:" + outer_x );
Private void display2 (){
System. out. println ("display outer_x:" + outer_x );
Void test (){
Inner inner = new Inner ();
Inner. display ();
Inner. display2 ();
// System. out. println ("Inner y:" + y); // internal variables cannot be accessed.
System. out. println ("Inner y:" + inner. y); // you can access
System. out. println ("Inner z:" + inner. z); // accessible
System. out. println ("Inner m:" + inner. m); // accessible
InnerTwo innerTwo = new InnerTwo ();
InnerTwo. show ();
Class InnerTwo {
Inner innerx = new Inner ();
Public void show (){
// System. out. println (y); // The Innter's y member cannot be accessed.
// System. out. println (Inner. y); // you cannot directly access any member or method of Inner.
Innerx. display (); // accessible
Innerx. display2 (); // accessible
System. out. println (innerx. y); // accessible
System. out. println (innerx. z); // accessible
System. out. println (innerx. m); // accessible
Public static void main (String args []) {
Outer outer = new Outer ();
Outer. test ();
The above code must be noted that for internal classes, public or private delimiters are usually not added before the class Keywords of the class are defined.
There is no impact, and it seems that these qualifiers have no impact on the internal class variables and methods (?). In addition, it should be noted that the internal class Inner and
InnterTwo is only known within the scope of the class Outer. If any code outside the class Outer tries to initialize the class Inner or use it, compilation will not
Yes. At the same time, the variable members of the internal class are only visible inside the internal. If the external class or the internal class at the same level needs to be accessed, the example program must be used.
And cannot directly access internal class variables.
4. Define internal classes in methods
The following code defines an internal class within the method:
Public class FunOuter {
Int out_x = 100;
Public void test (){
Class Inner {
String x = "x ";
Void display (){
System. out. println (out_x );
Inner inner = new Inner ();
Inner. display ();
Public void showStr (String str ){
// Public String str1 = "test Inner"; // It cannot be defined and can only be modified by final.
// Static String str4 = "static Str"; // It cannot be defined and can only be modified by final.
String str2 = "test Inner ";
Final String str3 = "final Str ";
Class InnerTwo {
Public void testPrint (){
System. out. println (out_x); // variables of the external class can be directly accessed.
// System. out. println (str); // non-final variables in this method cannot be accessed.
// System. out. println (str2); // non-final variables in this method cannot be accessed.
System. out. println (str3); // only the final variable member of this method can be accessed.
InnerTwo innerTwo = new InnerTwo ();
InnerTwo. testPrint ();
Public void use (){
// Inner innerObj = new Inner (); // Inner is invisible at this time.
// System. out. println (Inner. x); // Inner is invisible at this time.
Public static void main (String [] args ){
FunOuter outer = new FunOuter ();
Outer. test ();
From the above examples, we can see that the internal class defined in the method has less visibility, and it is only within the method.
It can be seen that external classes (and other methods of external classes) are invisible. At the same time, it has a feature: Method
Internal classes in the same method cannot access the member variables of this method. It can only access the final type members of this method. At the same time
It should be noted that the internal definition Member of the method only allows final modifier or without modifier, and other elements such as static are not available.
5. Anonymous internal class
The following code defines an anonymous internal class: The anonymous internal class is usually used for Java event processing.
Import java. applet .*;
Import java. awt. event .*;
Public class AnonymousInnerClassDemo extends Applet {
Public void init (){
AddMouseListener (new MouseAdapter (){
Public void mousePressed (MouseEvent me ){
ShowStatus ("Mouse Pressed! ");
Public void showStatus (String str ){
System. out. println (str );
In the preceding example, the addMouseListener method accepts an object-type parameter expression. Therefore, in the parameter, we define an anonymous internal class, which is a class of the MouseAdapter type, at the same time, this class defines an inherited method mousePressed. The entire class is used as a parameter. This class has no name, but is automatically instantiated when this expression is executed. At the same time, this anonymous internal class is defined in the AnonymousInnerClassDemo class, so it can access its showStatus method. This is consistent with the internal class above.
6. Other internal problems
Through the above, we can clearly see some usage methods of internal classes. At the same time, in many cases, internal classes are used as Java event processing or value objects. At the same time, we need to pay attention to the last problem, that is, the internal class is defined like other classes. It can also inherit the classes of other external packages and implement interfaces from other external places. It can also inherit other internal classes at the same level, or even inherit the external class itself. Let's end with the last example:
Public class Layer {
// Member variables of the Layer class
Private String testStr = "testStr ";
// Person class, base class
Class Person {
String name;
Public void setName (String nameStr ){
This. name = nameStr;
Public String getName (){
Return this. name;
Public void setEmail (Email emailObj ){
This. email = emailObj;
Public String getEmail (){
Return this. email. getMailStr ();
// Internal class of internal class, multi-layer internal class
Class Email {
String mailID;
String mailNetAddress;
Email (String mailId, String mailNetAddress ){
This. mailID = mailId;
This. mailNetAddress = mailNetAddress;
String getMailStr (){
Return this. mailID + "@" + this. mailNetAddress;
// Another internal class inherits the external class itself
Class ChildLayer extends Layer {
Void print (){
System. out. println (super. testStr); // access the member variable of the parent class
// Another internal class inherits the internal class Person
Class OfficePerson extends Person {
Void show (){
System. out. println (name );
System. out. println (getEmail ());
// External class test method
Public void testFunction (){
// Test the first internal class
ChildLayer childLayer = new ChildLayer ();
ChildLayer. print ();
// Test the second internal class
OfficePerson officePerson = new OfficePerson ();
OfficePerson. setName ("abner chai ");
// Note that the subclass object of the object must be generated using the object. new.
// Instead of Person. new Email (...)
// It is neither new Person. Email (...)
OfficePerson. setEmail (officePerson. new Email ("josserchai", " "));
OfficePerson. show ();
Public static void main (String [] args ){
Layer layer = new Layer ();
Layer. testFunction ();

Author: a125138

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: 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.