"49" Java Inner class anatomy

Source: Internet
Author: User
Tags class definition modifiers thread class java se

What is an internal class:

Classes defined in other classes (outer class) are referred to as inner classes. Inner classes can have access modifiers and can even be marked as abstract or final. Inner classes have special relationships with external class instances, which allow internal classes to access members of external classes, as well as private members.

The inner class is divided into the following four types:

Internal classes (inner class)
Local inner class
Anonymous inner class
Static nested classes

Why use an inner class: In the Think in Java there is this 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.

To illustrate:
 Public  interface Father {} Public  Interface mother {} Public  class Son implements Father, mother {} Public  class daughter implements 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 can solve multiple inheritance problems very well, but if we don't need to solve multiple inheritance problems, we can naturally use other coding methods, but using inner classes can also bring us the following features.

Below (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.

Inner class Syntax:

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

/**省略getter和setter方法**/  public class InnerClass{      public InnerClass(){          name = "chenssy";          age = 23;      }      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

 - 在这个应用程序中,我们可以看到内部了InnerClass可以对外围类OuterClass的属性进行无缝的访问,尽管它是private修饰的。这是因为当我们在创建某个外围类的内部类对象时,此时内部类对象必定会捕获一个指向那个外围类对象的引用,只要我们在访问外围类的成员时,就会用这个引用来选择外围类的成员。 - 其实在这个应用程序中我们还看到了如何来引用内部类:引用内部类我们需要指明这个对象的类型:OuterClasName.InnerClassName。同时如果我们需要创建某个内部类对象,必须要利用外部类的对象通过.new来创建内部类:OuterClass.InnerClass innerClass = outerClass.new InnerClass();。 - 同时如果我们需要生成对外部类对象的引用,可以使用OuterClassName.this,这样就能够产生一个正确引用外部类的引用了。当然这点实在编译期就知晓了,没有任何运行时的成本。

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. member Inner class:

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.

It is recommended to use GETXXX () to get the member inner class, especially if the constructor of the inner class has no arguments.
 Public classOuterclass {PrivateString str; Public void Outerdisplay() {System. out. println ("Outerclass ..."); } Public classinnerclass{ Public void Innerdisplay(){//Use properties inside the perimeterstr ="Chenssy ..."; System. out. println (str);//using methods in the peripheryOuterdisplay (); }      }/* We recommend using getxxx () to get the member inner class, especially when the constructor of the inner class has no arguments */       PublicInnerclassGetinnerclass(){return NewInnerclass (); } Public Static void Main(string[] args) {Outerclass outer =NewOuterclass ();          Outerclass.innerclass inner = Outer.getinnerclass ();      Inner.innerdisplay (); }}--------------------Chenssyouterclass
Local inner class

The local inner class is defined in the method of the outer class.

If you want to use an inner class, you must instantiate the inner class in the same method

Only both the abstract and final modifiers are allowed to decorate the local inner class

Inner classes are used only if the local variables of the method are marked as final or if the local variables are effectively final.
What is effectively final? "Starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that is final or E Ffectively final. A variable or parameter whose value is never changed after it was initialized is effectively final. "So when a variable or parameter is initialized, the value never changes again. The variable or parameter is effectively final.

//top level class definitionClass Myouterclassdemo {Private intx=1; Public void dothings() {String name ="local variable";//name is effectively final    //inner class defined inside a method of outer classClass Myinnerclassdemo { Public void Seeouter() {System. out. println ("Outer Value of X is:"+ x); System. out. println ("Value of name is:"+ name); }//close Inner class method}//Close inner class definitionMyinnerclassdemo inner =NewMyinnerclassdemo (); Inner.seeouter (); }//close Top Level class method  Public Static void Main(string[] args) {Myouterclassdemo outer =NewMyouterclassdemo (); Outer.dothings (); }}//Close Top level classOutput:outer Value of X is:1Value of Name is: local variable
Anonymous inner class: Anonymous inner class has the following characteristics:

No name.
Can only be instantiated once
is usually declared inside a method or block of code, ending with a semicolon-delimited curly brace
Because there is no name, there is no constructor
Cannot be static

Why use anonymous classes, let's look at an example:
Abstract  class Animal {    Abstract voidPlay ();} class Dog extends Animal{    voidPlay () {System.out.println ("Play with Human"); }} class Demo{     Public Static voidMain (string[] args) {Animal d =NewDog ();    D.play (); }}output:play with Human

If the dog class here is used only once, is it a little cumbersome to define a single dog class? At this point we can introduce anonymous classes:

abstractclass Animal {    abstractvoid play();}class Person{    publicstaticvoid main(String[] args){        new Animal(){            void play(){                System.out.println("play with human");            }        };        d.play();    }}Output:  play with human
An important function of an anonymous class is to simplify the code. Common scenarios for anonymous classes: 1. Event monitoring: A common implementation method:
publicclass WindowClosingAdapter extends WindowAdapter {     publicvoidwindowClosing( WindowEvent e ) {         System.exit(0);     new WindowClosingAdapter() );
How anonymous inner classes are implemented:
 addWindowListener(     new WindowAdapter() {         publicvoidwindowClosing( WindowEvent e ) {             System.exit(0);         }     });
Anonymous inner class implementations of the 2.Thread class
publicclass Demo {    publicstaticvoidmain(String[] args) {        new Thread() {            publicvoidrun() {                for (int15; i++) {                    System.out" ");                }            }        };        t.start();    }

}

Anonymous inner class implementation of the Runnable interface
publicclass Demo {    publicstaticvoidmain(String[] args) {        new Runnable() {            publicvoidrun() {                for (int15; i++) {                    System.out" ");                }            }        };        new Thread(r);        t.start();    }}
Anonymous inner classes need to be aware of:

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.

Static nested classes

Static can decorate member variables, methods, blocks of code, and other it can also decorate inner classes, and internal classes that use static adornments we call static inner classes, but we prefer to call them nested inner classes. 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、 它的创建是不需要依赖于外围类的。      2、 它不能使用任何外围类的非static成员变量和方法。
 class Outer{   Static  class Nested{A static nested class can be instantiated like this: class Outer{//Outer class   Static  class Nested{}//static nested class} class Demo{    Public Static voidMainstring[] args) {//Use both class namesOuter.nested n=NewOuter.nested (); }}
Reference blog:

http://liuzxc.github.io/blog/java-advance-02/
http://blog.csdn.net/chenssy/article/details/13024951

Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. Sweep my QR code plus me

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

"49" Java Inner class anatomy

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.