Java Nested Class (Nested Class): Static nested class, inner class, local class, anonymous class

Source: Internet
Author: User



Comparing a person to a class, a person is composed of a brain, a limb, an organ, and a nested class is equivalent to one of its organs, such as a heart: it also has its own properties and behavior (blood, beating).






Structure of nested classes (Nested Class):


/ / external class
Class Out {
private int age = 12;
/ / nested class
Class In {
public void print() {
System.out.println(age);
}
}
}
public class Demo {
public static void main(String[] args) {
Out.In in = new Out().new In();
In.print ();
//Or visit in the following way
/ *
Out out = new Out();
Out.In in = out.new In();
In.print ();
* /
}
}


Operation Result: A



Benefits of Nested classes:



1 Logically grouping classes used only in one place



2 Increased encapsulation (encapsulation)



3 Make your code more readable and easier to maintain






Nested classes are divided into statically nested classes (static nested Class) and non-static nested classes (Non-static nested Class), which are also called inner classes (inner Class).






Example 1. Static nested classes





<span style="font-size:14px;">class Out {

    private static int age = 12;

     

    static class In {

        public void print() {

            System.out.println(age);

        }

    }

}

 

public class Demo {

    public static void main(String[] args) {

        Out.In in = new Out.In();

        in.print();

    }

}</span>
Run Result: 12





Note: If you statically internal static, the inner class can only access static member variables of the outer class, with limitations. Second, because the inner class is statically, the out.in can be viewed as a whole, and can be directly new to the object of the inner class.






Example 2. Inner class


Class Out {
private int age = 12;
Class In {
private int age = 13;
public void print() {
int age = 14;
System. Out. Println ("local variable:" + age);
System. Out. Println ("internal class variable:" + this. Age);
System. Out. Println ("external class variable:" + out. This. Age);
}
}
}
public class Demo {
public static void main(String[] args) {
Out.In in = new Out().new In();
In.print ();
}
}


Operation Result:



Local variables: 14
Internal class variable: 13
External class variables: 12



It can be found that, in the case of an inner class without a member variable and a local variable of the same name, the inner class accesses the member variable of the outer class directly without specifying Out.this. Property name



Otherwise, local variables in the inner class will overwrite the member variables of the outer class.



The member variables that access the inner class itself are available with this. Property name, and access to the member variables of the external class requires the use of the Out.this. Property name.






There are also two special inner classes: The local class and the anonymous (anonymous class)



A local class is a class that is defined in a block of code, usually within a method, called a method inner class.



The Declaration and instantiation of an anonymous class is done at the same time, similar to a local class, except that there is no name.






Example 3. Local class


class Out {

    private int age = 12;

 

    public void Print(final int x) {

        class In {

            public void inPrint() {

                System.out.println(x);

                System.out.println(age);

            }

        }

        new In().inPrint();

    }

}

 

public class Demo {

    public static void main(String[] args) {

        Out out = new Out();

        out.Print(3);

    }

}

运行结果:

3

12


在上面的代码中,将内部类移到了外部类的方法中,然后在外部类的方法中再生成一个内部类对象去调用内部类方法。


例4. 匿名类

public class OutClasses {
  
    interface HelloWorld {
        public void greetSomeone(String someone);
    }
  
    public void sayHello() {
        
        HelloWorld germanGreeting = new HelloWorld() {//这里申明了一个匿名类,它的实例是germanGreeting
            String name = "mundo";
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hallo, " + name);
            }
        };
        germanGreeting.greetSomeone("Sommer");
    }

    public static void main(String... args) {
        OutClasses myApp = new OutClasses();
        myApp.sayHello();
    }            
}


Operation Result:



3



12






In the preceding code, the inner class is moved to the method of the outer class and then regenerated into an inner class object in the method of the outer class to invoke the inner class method.






Example 4. Anonymous class


public class Outclasses {      interface HelloWorld {public        void Greetsomeone (String someone);    }      public void SayHello () {                HelloWorld germangreeting = new HelloWorld () {//here declares an anonymous class whose instance is Germangreeting            String name = "Mundo";            public void Greetsomeone (String someone) {                name = someone;                System.out.println ("Hallo," + name);            }        ;        Germangreeting.greetsomeone ("Sommer");    }    public static void Main (String ... args) {        outclasses myApp = new outclasses ();        Myapp.sayhello ();    }            }


Running Result: Hallo,sommer






An anonymous class is an expression (a semicolon-terminated) that is common in GUI applications. Its syntax is similar to invoking a constructor, except that the definition of the class is immediately followed. How can you tell about anonymous classes without the class keyword?



1) to have the new operator, similar to the normal class instantiation of an expression.



2) to implement an interface or inherit a class, the example above is to implement the HelloWorld interface.



3) class body (body), where you can define fields, methods, or even partial classes, but you cannot define constructors or have statements (statement).






This section of this article refers to Nerxious's blog http://www.cnblogs.com/nerxious/archive/2013/01/24/2875649.html



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



Java Nested Class (Nested Class): Static nested class, inner class, local class, anonymous class


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.