Java Improvement Chapter (VII)-----detailed internal class

Source: Internet
Author: User
Tags static class

You can place the definition of a class within the definition of another class, which is the inner class.

The inner class is a very useful feature but it is rather difficult to understand the use of the features (I do not have how to use the internal class, the internal class is also just inkling). first time to meet

Inner class It is very easy to understand from the outside, it is to define a class within a class.

public class Outerclass {
    private String name;
    private int age;

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    public int getage () {return age
        ;
    }

    public void Setage (int age) {
        this.age = age;
    }
    
    Class innerclass{public
        innerclass () {
            name = "Chenssy";
            age =%;}}

Here Innerclass is the inner class, for beginners, the internal class is not used much, I rookie a also not how to use (seemingly only to do swing registration events used), but with the improvement of programming ability, we will understand its charm, It can be used to design our program structure more elegantly. Between using inner classes we need to understand why internal classes can benefit us by using the inner class.


Why should I use the inner class

Why do I use an inner class? One of the most compelling reasons to use inner classes is that each inner class inherits an (interface) implementation independently, so it has no effect on the inner class, regardless of whether the outer class has inherited an (interface) implementation.

There are sometimes problems with interfaces that are difficult to solve in our programming, when we can solve these programming problems with the ability of internal classes to inherit multiple concrete or abstract classes. It can be said that the interface solves only some of the problems, while the inner class makes the multiple-inheritance solution more complete.

Public interface Father {

} public interface Mother {} Public classes Son implements Father

, Mother {

} Public

class daughter implements father{

    class Mother_ implements
        
    }
}

In fact, we do not see the advantages of using inner classes for this instance, but if father, mother are not interfaces, but abstract classes or concrete classes. This time we can only use the inner class to achieve multiple inheritance.

The great advantage of using an 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 an inner class can also bring us the following features (excerpt from "Think in Java"):

1, the internal class can use multiple instances, each instance has its own state information, and other peripheral objects of information 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 internal class object does not depend on the creation of a peripheral class object.

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

5, the internal class provides a better encapsulation, in addition to this peripheral class, other classes are inaccessible.


Ii. internal types of foundation

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

When we create an inner class, it virtually has a connection to the outer class, depending on the connection, which allows unrestricted access to the elements of the outer class.

public class Outerclass {
    private String name;
    private int age;

    /** ellipsis getter and setter method **/public
    
    class innerclass{public
        innerclass () {
            name = "Chenssy";
            Age = N
        }
        
        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 the internal innerclass can make seamless access to the properties of the perimeter class Outerclass, although it is private-decorated. This is because when we create an inner class object of a peripheral class, the inner class object is bound to capture a reference to that outer class object, and as long as we are accessing the members of the outer class, we use this reference to select the members of the outer class.

In fact, we also see how to refer to an inner class in this application: referencing the inner class we need to indicate the type of the object: Outerclasname.innerclassname. Also, if we need to create an inner class object, we must use the object of the outer class to create the inner class by using the. NEW: Outerclass.innerclass innerclass = Outerclass.new innerclass ();.

Also, 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 known, there is no run-time costs.

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 be clear, the inner class is a compile-time concept, and once the compilation succeeds, it belongs to two completely different classes of the outer class (of course they are still connected). For a peripheral class named Outerclass and an inner class named Innerclass, after the compilation succeeds, there are two class files: Outerclass.class and Outerclass$innerclass.class.

In Java, internal classes are mainly divided into members internal classes, local internal classes, anonymous internal classes, static internal classes.


third, the member internal class

The member inner class is also the most common inner class, it is a member of the outer class, so he is unrestricted access to all the member properties and methods of the outer class, although private, but the outer class has to access the member properties and methods of the inner class to be accessed through an internal class instance.

Be aware of two points in a member's inner class, first: no static variables and methods can exist within a member's class; second: members ' inner classes are attached to the outer class, so the inner class can be created only if the outer class is created first.

public class Outerclass {
    private String str;
    
    public void Outerdisplay () {
        System.out.println ("Outerclass ...");
    }
    
    public class innerclass{public
        void Innerdisplay () {
            //using the attributes in the perimeter
            str = "Chenssy ...";
            System.out.println (str);
            Use the method inside the perimeter
            outerdisplay ()
        ;
    }
    
    /* recommends using 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 that you use GETXXX () to get the member inner class, especially when the constructor of the inner class has no parameters.


Four, the local internal class

There is an inner class that is nested within the method and function, 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 public, so we have a local internal class, the local class and members of the inner class are compiled, Only its scope has changed, it can only be used in the method and the property, the method and the property will be invalidated.

There is really no good example of a local inner class, so just cite the classic example in "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 in 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 doing swing programming, we often use this approach to bind events

Button2.addactionlistener (  
                new ActionListener () {public  
                    void actionperformed (ActionEvent e) {  
                        System.out.println ("You press the button two");  
                    }  
                );

We may find it very strange, because this inner class is not named, looking at 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: 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 is first to exist. If we comment out that Innerclass interface, there will be a compilation error.

3 . Note The formal parameters of the Getinnerclass () method, the first formal parameter is decorated with final, and the second is not. We also find that the second parameter is not used in the anonymous inner class, so the formal parameter must be final when the formal parameter of the method is used by the 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 internal class is introduced here, for more information on anonymous internal classes, I will be in the next blog (Java improve-----Detailed anonymous internal classes) do a detailed introduction, including why the formal parameters to be defined as final, How to initialize anonymous inner class and so on, please look forward to ...


VI. Static internal class

In the Java enhancement-----keyword static, which refers to static can modify member variables, methods, blocks of code, other it can also modify the inner class, the use of static modified inner class we call static inner class, but we prefer to call it a nested inner class. One of the biggest differences between static internal classes and non-static inner classes is that we know that non-static inner classes implicitly hold a reference after compilation completes, pointing to the perimeter of the creation, but not the static inner class. Without this reference, it means:

1, the creation of it does not need to rely on peripheral classes.

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

public class Outerclass {private String sex;
    
    public static String name = "Chenssy"; /** * Static Internal class */static Class innerclass1{/* Static members can exist in static internal classes/public static String _name1 =
        
        "Chenssy_static";
             public void display () {/* * static inner class can only access static member variables and methods of the perimeter class * Non-static member variables and methods for peripheral classes cannot be accessed
        */System.out.println ("Outclass name:" + name); }/** * Non-static internal class/class innerclass2{/* non-static inner class cannot exist static member/public String _nam
        E2 = "Chenssy_inner"; /* A non-static inner class can invoke any member of the perimeter class, whether static or non-static/public void display () {System.out.println ("Outerclass Name:" +
        name); }/** * @desc Peripheral class method * @author Chenssy * @data 2013-10-25 * @return void * */Pub
        LIC void display () {/* Outer class Access static inner class: inner class. */System.out.println (INNERCLASS1._NAME1);
 /* Static internal classes can create instances directly without relying on peripheral classes * *       New InnerClass1 (). display ();
        /* Non-static internal creation needs to rely on the perimeter class * * Outerclass.innerclass2 Inner2 = new Outerclass (). New InnerClass2 ();
        /* The member of the non static inner class needs to use an instance of the Non-static inner class/System.out.println (INNER2._NAME2);
    Inner2.display ();
        public static void Main (string[] args) {outerclass outer = new Outerclass ();
    Outer.display (); }}----------------output:chenssy_static outclass name:chenssy chenssy_inner outerclass Name:chenssy

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

The introduction of the inner class here is basically over. For the internal class actually I know also just fur, approximation rookie one, cognitive limited. I will use these days to study the inner class!

Consolidate the foundation, improve technology, do not fear difficulties, climb the peak ...

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.