JAVA Inner Class (ii)

Source: Internet
Author: User

First, why to use the internal class

Why use internal classes? In "Think in Java" There is a sentence: the most appealing reason for using inner classes is that each inner class can inherit one (interface) implementation independently, so no matter whether the perimeter class has inherited an implementation of (an interface), there is no effect on the inner class.

In our programming, there are some problems that are difficult to solve by using interfaces, and we can use internal classes to provide the ability to inherit multiple concrete or abstract classes to solve these programming problems. It can be said that the interface only solves some of the problems, while the inner classes make multiple inheritance solutions more complete.

Public interface Father {}public interface mother {}public class Son implements Father, mother {}public class daughter Imp Lements father{    class Mother_ implements mother{            }}

In fact, for this example we do not see what the advantages of using the inner class, but if father, mother is not an interface, but abstract class or concrete class? At this point, we can only use the inner class to achieve multiple inheritance.

In fact, the greatest advantage of using the inner class is that it solves multiple inheritance problems very well, but if we don't need to solve multiple inheritance problems, we can naturally use other encodings, but using internal classes can also give us the following features (from Think in Java):

1 . The inner class can use multiple instances, each with its own state information, and the information of other peripheral objects is independent of each other.

2 . In a single perimeter class, you can have multiple inner classes implement the same interface in different ways, or inherit the same class.

3 . The time to create an inner class object does not depend on the creation of the perimeter class object.

4, the inner class does not have the confusing "is-a" relationship, he is an independent entity.

5 . The inner class provides a better encapsulation, except for the perimeter class, which cannot be accessed by other classes.

Second, the internal class basis

In this section, we mainly describe how the inner classes use the properties and methods of the external classes, as well as using. This and. New.

When we create an inner class, it implicitly has a connection to the perimeter class, which relies on this connection, which allows unrestricted access to the elements of the enclosing class.

public class Outerclass {    private String name;    private int age;    /** omit getter and setter methods **/public        class innerclass{public        innerclass () {            name = "Chenssy";            age = All;        }                public void display () {            System.out.println ("Name:" + getName () + "   ; Age:" + getage ());        }    }        public static void Main (string[] args) {        Outerclass outerclass = new Outerclass ();        Outerclass.innerclass innerclass = Outerclass.new innerclass ();        Innerclass.display ();    }} --------------Output:name:chenssy   ; age:23

In this application, we can see that inside the Innerclass can seamlessly access the properties of the perimeter class Outerclass, although it is private decorated. This is because when we create an inner class object of a perimeter class, the inner class object must capture a reference to that outer class object, as long as we access the members of the perimeter class, we use this reference to select the members of the perimeter class.

In fact, in this application we also see how to refer to inner classes: referencing inner classes We need to indicate the type of the object: Outerclasname.innerclassname. At the same time, if we need to create an inner class object, we must create an inner class with an object of the outer class through. NEW: Outerclass.innerclass innerclass = Outerclass.new innerclass ();.

At the same time, if we need to generate a reference to an external class object, we can use outerclassname.this so that we can produce a reference that correctly references the external classes. Of course, this is a compile-time knowing that there is no runtime cost.

public class Outerclass {public    void display () {        System.out.println ("Outerclass ...");    }        public class innerclass{Public        outerclass Getouterclass () {            return outerclass.this;        }    }        public static void Main (string[] args) {        Outerclass outerclass = new Outerclass ();        Outerclass.innerclass innerclass = Outerclass.new innerclass ();        Innerclass.getouterclass (). display ();}    } -------------Output:outerclass ...

Here we need to make it clear that the inner class is a compile-time concept, and once it's compiled, it's two completely different classes from the perimeter class (of course they're still connected). For a perimeter class named Outerclass and an inner class named Innerclass, two class files such as Outerclass.class and Outerclass$innerclass.class appear after the compilation succeeds.

In Java, the inner class is mainly divided into member inner class, local inner class, anonymous inner class, static inner class.

Iii. internal categories of members

The member inner class is also the most common inner class, which is a member of the perimeter class, so he can access all the member properties and methods of the perimeter class without restrictions, although it is private, but the perimeter class accesses the member properties and methods of the inner class through an internal class instance.

There are two points to note in a member's inner class, first: no static variables and methods exist in the member's inner class, and the second: the member inner class is attached to the outer class, so only the perimeter class is created first to be able to create the inner class.

public class Outerclass {    private String str;        public void Outerdisplay () {        System.out.println ("Outerclass ...");        public class innerclass{public        void Innerdisplay () {            //using properties inside the perimeter            str = "Chenssy ...";            System.out.println (str);            Use the method inside the perimeter            outerdisplay ();        }    }        /* It is recommended to use GETXXX () to get the member inner class, especially when the constructor of the inner class has no arguments */public    Innerclass Getinnerclass () {        return new innerclass ();    } Public        static void Main (string[] args) {        outerclass outer = new Outerclass ();        Outerclass.innerclass inner = Outer.getinnerclass ();        Inner.innerdisplay ();    }} --------------------Chenssy...outerclass ...

It is recommended to use GETXXX () to get the member inner class, especially if the constructor of the inner class has no arguments.

Iv. Local Internal classes

There is an inner class, it is nested in the method and action, for the use of this class is mainly to apply and solve more complex problems, want to create a class to assist our solution, and then do not want this class is publicly available, so it produced a local inner class, local inner class and member inner class is compiled, Only its scope has changed, it can only be used in the method and properties, the method and the property will be invalidated.

There is no good example of a local inner class, so we cite the classic example of Think in Java.

Defined in the method:

public class Parcel5 {public    destionation destionation (String str) {        class Pdestionation implements destionation{            private String label;            Private Pdestionation (String whereto) {                label = Whereto;            }            Public String Readlabel () {                return label;            }        }        return new pdestionation (str);    }        public static void Main (string[] args) {        Parcel5 parcel5 = new Parcel5 ();        Destionation d = parcel5.destionation ("Chenssy");}    }

Defined within the scope:

public class Parcel6 {    private void internaltracking (Boolean b) {        if (b) {            class trackingslip{                private String ID;                Trackingslip (String s) {                    id = s;                }                String Getslip () {                    return ID;                }            }            Trackingslip ts = new Trackingslip ("Chenssy");            String string = Ts.getslip ();        }    }        public void Track () {        internaltracking (true);    }        public static void Main (string[] args) {        Parcel6 parcel6 = new Parcel6 ();        Parcel6.track ();    }}

Five, anonymous internal class

In swing programming, we often use this way to bind events

Button2.addactionlistener (                  new ActionListener () {public                      void actionperformed (ActionEvent e) {                          SYSTEM.OUT.PRINTLN ("You pressed button two");                      }                  );

We may find it very strange, because this inner class is not a name, see the following example:

public class Outerclass {public    innerclass getinnerclass (final int num,string str2) {        return new Innerclass () { C2/>int number = num + 3;            public int GetNumber () {                return number;            }        };        /* Note: The semicolon cannot save */    } public        static void Main (string[] args) {        outerclass out = new Outerclass ();        Innerclass inner = out.getinnerclass (2, "Chenssy");        System.out.println (Inner.getnumber ());}    } Interface Innerclass {    int getnumber ();} ----------------Output:5

Here, we need to see a few places.

1 . Anonymous inner class is not an access modifier.

2, new anonymous inner class, this class first is to exist. If we comment out the Innerclass interface, there will be a compile error.

3, note the formal parameters of the Getinnerclass () method, the first parameter is final decorated, and the second is not. We also find that the second parameter is not used in the anonymous inner class, so the formal parameter of the method must be final if it needs to be used by an anonymous inner class.

4, anonymous inner class is not constructed method. Because it doesn't even have a name to construct the method.

PS: due to the limited space, the anonymous inner class is introduced here, for more on the anonymous inner class knowledge, I will be in the next blog (Java improved-----the anonymous inner class) to do a detailed introduction, including why the formal parameters to be defined as final, How to initialize anonymous internal classes, etc., and so on, please look forward to ...

Vi. Static Internal classes

In the Java-----keyword static mentions that static can decorate member variables, methods, code blocks, other it can also decorate the inner class, using static decorated inner class we call static inner class, but we prefer to call it nested inner class. There is one big difference between static inner and non-static inner classes, and we know that a non-static inner class implicitly holds a reference after compilation, which points to the perimeter in which it was created, but does not have a static inner class. Without this reference, it means:

1, its creation is not required to rely on the peripheral class.

2 . It cannot use non-static member variables and methods of any perimeter class.

public class Outerclass {private String sex;        public static String name = "Chenssy"; /** * Static INNER class */Static Class innerclass1{/* Static member can exist in static inner class */public static String _name1 = "Chen                Ssy_static ";             public void display () {/* * static inner class can only access static member variables and methods of the perimeter class * Cannot access non-static member variables and methods of the perimeter class */        System.out.println ("Outclass name:" + name); }}/** * Non-static inner class */class innerclass2{* * Non-static inner class cannot exist static member */public String _name2 = "ch        Enssy_inner "; /* Any member of the perimeter class can be called in a non-static inner class, whether static or non-static */public void display () {System.out.println ("Outerclass name:" + NA        ME); }}/** * @desc outer class method * @author Chenssy * @data 2013-10-25 * @return void */public void        Display () {/* * Peripheral class accesses static inner class: inner class. */System.out.println (INNERCLASS1._NAME1);       /* Static inner classes can create instances directly without the need to rely on the perimeter class */New InnerClass1 (). display ();         /* Non-static internal creation needs to depend on the perimeter class */outerclass.innerclass2 Inner2 = new Outerclass (). New InnerClass2 ();        /* Members of non-static inner classes need to use instances of non-static inner classes */System.out.println (inner2._name2);    Inner2.display ();        } public static void Main (string[] args) {outerclass outer = new Outerclass ();    Outer.display (); }}----------------Output:chenssy_staticoutclass Name:chenssychenssy_innerouterclass Name:chenssy

The above example shows the difference between static inner classes and non-static inner classes.

JAVA Inner Class (ii)

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.