Java InnerClass (innerclass) ---- non-static internal class, static internal class, local internal class, anonymous internal class, Department class InnerClass

Source: Internet
Author: User

Java InnerClass (innerclass) ---- non-static internal class, static internal class, local internal class, anonymous internal class, Department class InnerClass

Many people are not familiar with the java underwear Class. In fact, similar concepts also exist in c ++, that is, the Nested Class. What are the differences between these two classes, the following is a comparison. On the surface, the internal class defines a class in the class (as we can see below, the internal class can be defined in many places), but it is actually not that simple, at first glance, the internal class seems a little redundant. His use may not be so significant for beginners, but with his deep understanding, you will find that java designers have a great deal of effort in the underwear category. Learning to use internal classes is part of advanced java programming. It allows you to design your program structure more elegantly. The following describes how:

First meeting:

public class TestInnerClass{    public static void main(String args[]){        Goods good = new Goods();                Contents content = good.dest();        System.out.println(content.value());                Destination destination = good.cont("BeiJing");        System.out.println(destination.readLabel());    }}interface Contents{    int value();}interface Destination{    String readLabel();}class Goods{    private class Content implements Contents{        private int i = 11;        public int value(){            return i;        }    }    protected class GDestination implements Destination{        private String label;        private GDestination(String whereTo){            label = whereTo;        }        public String readLabel(){            return label;        }    }    public Content dest(){        return new Content();    }    public GDestination cont(String s){        return new GDestination(s);    }}

 

In this example, the class Content and GDestination are defined in the Goods class and have private and protected modifiers respectively to control the access level. Content represents Goods Content, while GDestination represents Goods destination. In the following main () method, you can use Contents content and Destination destination to perform operations. You have never even seen the names of these two internal classes, the benefits of internal classes are embodied, hiding the operations you don't want others to know, that is, encapsulation.

At the same time, we also found that the first method to get internal class objects out of the scope of the external class is to create and return using its external class method. In the preceding example, the dest () and cont () methods do this. So, is there any other way? Of course, the syntax format is as follows:

OuterClass outerObject = new OuterClass (Constructor parameters );

OuterClass. InnerClass innerObject = outerObject. new InnerClass (Constructor parameters); // Of course, at this time, we need to change the number of constructed lines of the internal class to public instead of private.

Note that when creating a non-static internal class object, you must first create an external class object. As for the reason, it will lead to our next topic that non-static internal class objects have references pointing to their external class objects. I will slightly modify the example just now:

public class TestInnerClass{    public static void main(String args[]){        Goods good = new Goods();                Contents content = good.dest();        System.out.println(content.value());    }}interface Contents{    int value();}interface Destination{    String readLabel();}class Goods{        private int valueRate = 2;    private class Content implements Contents{        private int i = 11 * valueRate;        public int value(){            return i;        }    }    protected class GDestination implements Destination{        private String label;        public GDestination(String whereTo){            label = whereTo;        }        public String readLabel(){            return label;        }    }    public Content dest(){        return new Content();    }    public GDestination cont(String s){        return new GDestination(s);    }}

Here we add a new private member variable valueRate to Goods, which indicates the value coefficient of the Goods. When the value () method of Content in the internal class calculates the value, it is multiplied. We found that value () can access valueRate, which is the second advantage of the internal class. An internal class object can access the content of the external class object that creates it, and even include private variables! This is a very useful feature that provides us with more ideas and shortcuts during design. To implement this function, internal class objects must have references to external class objects.

When creating an internal class object, the java compiler implicitly transfers the objects of other external classes and stores them all the time. In this way, internal class objects can always access their external class objects. This is also why external class objects must be created to create internal class objects out of the scope of the external class.

Someone may ask, what if a member variable of an external class has the same name as a member variable of an internal class, that is, the member variable of the external class is blocked? Nothing. the following format is used in java to express reference of external classes:

OuterClass. this

With it, we are not afraid of such blocking.

Static internal class

Like normal classes, internal classes can also be static. However, compared with non-static internal classes, the difference is that static internal classes do not reference external classes. This is actually very similar to the nested class in c ++. The biggest difference between a java internal class and a c ++ nested class is whether it points to external class references. Of course, there are some differences from the design details and some other perspectives.

In addition, no non-static internal class can have static data, static methods, or another static internal class (internal class nesting can be more than one layer ). However, static internal classes can have everything. This is also the second difference between the two.

Local internal class:

Yes, java internal classes can be defined in a method or even a code block.

public class TestInnerClass{    public static void main(String args[]){        Goods good = new Goods();                Destination destination = good.dest("beijing");        System.out.println(destination.readLabel());    }}interface Destination{    String readLabel();}class Goods{    public Destination dest(String s){        class GDestination implements Destination{            private String label;            public GDestination(String whereTo){                label = whereTo;            }            public String readLabel(){                return label;            }        }        return new GDestination(s);    }}

The above is an example. In the dest () method, we define an internal class, And finally this internal class is returned by this method. If we only need to create an object and create it to the external when creating an object, we can do this. Of course, the internal class defined in the method can diversify the design, and its purpose is not only in this regard.

The following is a more strange example:

 

public class TestInnerClass{    private void into(boolean b){        if(b){            class GDestination {                private String label;                public GDestination(String whereTo){                    label = whereTo;                }                public String readLabel(){                    return label;                }                }            GDestination destination = new GDestination("beijing");            System.out.println(destination.readLabel());        }    }    public void dest(boolean b){        into(b);    }    public static void main(String args[]){        TestInnerClass inner = new TestInnerClass();        inner.dest(true);    }}

You cannot create an internal Class Object outside of the if () statement. It should be beyond its scope. However, during compilation, the internal class GDestination is compiled at the same time as other classes, but it has its own scope. If it exceeds this range, it is invalid. It is no different from other internal classes.

Anonymous internal class

The anonymous internal class of java looks odd, but just like an anonymous array, when you only need to create a Class Object and cannot use its name, using Internal classes seems to make the code more concise and clear. Its syntax rules are as follows:

New interfaceName (){...................}; or: new superClassName () {................................};

Next we will continue with the example above:

public class TestInnerClass{    public Contents cont(){        return new Contents(){            private int i = 11;            public int value(){                return i;            }        };    }    public static void main (String args[]){        TestInnerClass test = new TestInnerClass();        Contents content = test.cont();                System.out.println(content.value());    }}interface Contents{    public int value();}

Here, the cont () uses an anonymous internal class to directly return a Class Object implementing the Contents interface, which looks very concise.

In the anonymous adapter of java's event processing mechanism, anonymous internal classes are widely used. For example, add the following code when closing the window:

frame.addWindowListener(new WindowAdapter(){      public void windowClosing(WindowEvent e){         System.exit(0);      }  });   

One thing to note is that the anonymous internal class does not have a name, so it does not have a constructor (but if this anonymous internal class inherits a parent class that only contains a constructor with parameters, these parameters must be included during creation and the corresponding content must be called using the super keyword during implementation ). If you want to initialize its member variables, you can use the following methods:

If you are using an anonymous internal class of a method, you can use this method to pass in the desired parameters, but remember that these parameters must be declared as final.

The anonymous internal class is transformed into a local internal class with a name, so that it can have constructor.

Use the initialization code block in this anonymous internal class.

Why Internal classes?

What are the advantages of java internal classes? Why Internal classes?

First, let's take a simple example. If you want to implement an interface, but a method in this interface has the same name and parameter as a method in the class you have conceived, what should you do? At this time, you can create an internal class to implement this interface. Because the internal class can access all the content of the external class, you can directly implement this interface.

But you may have to question it. Can you just change the method?

Indeed, the reason for designing the internal class is unconvincing.

The real reason is that the combination of internal classes and interfaces in java can solve a problem that is often complained by C ++ programmers that java has not inherited much. In fact, the multi-inheritance design of c ++ is complex, and java can achieve multi-inheritance through internal classes + interfaces.


What are the characteristics and functions of local and anonymous internal classes in JAVA? I 'd better explain it in detail.

Java internal class
There are four types: Member internal class, local internal class, static internal class, and anonymous internal class.
1. Member internal class: a member of an external class, which is in parallel with the attributes and methods of the external class.
Note: static variables cannot be defined in the member's internal class, but all members of the external class can be accessed.
Public class Outer {
Private static int I = 1;
Private int j = 10;
Private int k = 20;
Public static void outer_f1 (){
// Do more something
}
Public void out_f2 (){
// Do more something
}

// Member internal class
Class Inner {
// Static int inner_ I = 100; // static variables cannot be defined in the internal class
Int j = 100; // instance variables of internal and foreign departments can coexist.
Int inner_ I = 1;
Void inner_f1 (){
System. out. println (I); // If the variable of the external class does not have the same name as the variable of the internal class, you can directly use the variable name to access the variable of the external class.
System. out. println (j); // directly use the variable name to access the internal class's own variables in the internal class
System. out. println (this. j); // you can also use "this. variable name" in the internal class to access internal class variables.
// Access the instance variables with the same name as the internal class in the external class. You can use "external class name. this. variable name ".
System. out. println (k); // If the variable of the external class does not have the same name as the variable of the internal class, you can directly use the variable name to access the variable of the external class.
Outer_f1 ();
Outer_f2 ();
}
}
// Access the internal class of the member using non-static methods of the external class
Public void outer_f3 (){
Inner inner = new Inner ();
Inner. inner_f1 ();
}

// The static method of the external class accesses the internal class of the member, which is the same as the internal class of the external class access member.
Public static void outer_f4 (){
// Step 1 create an external Class Object
Outer out = new Outer ();
// *** Step 2: create an internal class object based on the external Class Object ***
Inner inner = out. new Inner ();
// Step 3: Access the internal class
Inner. inner_f1 ();
}

Public static void main (String [] args ){
Outer_f4 ();
}
}
Advantages of member Internal classes:
(1) The internal class acts as a member of the external class and can access the private members or attributes of the external class. (Even if the external class is declared as PRIVATE, it is still visible to internal classes .)
(2) Use an internal class to define inaccessible attributes of an external class. In this way, the external class has lower access permissions than the external class's private.
Note: Internal classes are a compilation concept. Once compiled successfully, they become completely different. For an external class named outer and its internal defined internal class named inner. After compilation is complete, the outer. class... remaining full text appears>

Java internal class

In java, there is a kind of class called inner class, also known as nested class, which is defined inside other classes. An internal class is a member of its external class. Like other members, it can directly access the data and methods of its external class. However, compared with external classes, only public and default modifiers are different. An internal class can be any modifier as a member. During compilation, the internal class name is OuterClass $ InnerClass. class.

1. Internal class Access Data Variables
In some cases, when the variables defined in the internal class are the same as those in the external class, how can we ensure correct access to every variable?

1.1 calling internal class methods directly from external classes in main

Class Outer
{
Private int index = 10;
Class Inner
{
Private int index = 20;
Void print ()
{
Int index = 30;
System. out. println (this); // the object created from the Inner
System. out. println (Outer. this); // the object created from the Outer
System. out. println (index); // output is 30
System. out. println (this. index); // output is 20
System. out. println (Outer. this. index); // output is 10
}
}

Void print ()
{
Inner inner = new Inner (); // get internal class reference
Inner. print ();
}
}

Class Test
{
Public static void main (String [] args)
{
Outer outer = new Outer ();
Outer. print ();
}
}
Here, the internal class Inner keyword this points to the internal class Inner object. to point to the external class object, you must add the external class name before the this pointer, indicates that this is the debris that points to the external class structure, such as Outer. this.

1.2 explicitly returning internal class references in main

Class Outer
{
Private int index = 10;
Class Inner
{
Private int index = 20;
Void print ()
{
Int index = 30;
System. out. println (index );
System. out. println (this. index );
System. out. println (Outer. this. index );
}
}

... The remaining full text>

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.