Java Internal class

Source: Internet
Author: User

Inner-class explanation
1. Definition
The definition of a class is placed inside another class, and this class is called an inner class.

Java code
public class First {public  class contents{public      void F () {      System.out.println ("in class first ' s inner class Contents method F () ");}}     


Like this, contents is called an inner class.
Inner classes understand the perimeter class and can communicate with it (in detail later)

2. Link to peripheral class
When an inner class object is created, it has a connection to the perimeter object that created it, so it can access all members of the perimeter class without any special conditions.

Java code
public class First {public  class contents{public           void Getstr () {          System.out.println ("first.str=" +str);       }  }  Private String str;      }  


In the inner class contents, you can use the field of the outer class first Str.
So, how is it implemented?
So, when you create an inner class object with a perimeter class, the inner class object secretly captures a reference to the perimeter class, so you can access the members of the perimeter class through this reference.
Usually, these are compilers to deal with, we don't see, and don't care about this.
Because of this, when we create an inner class object, we must associate it with the perimeter class object.
Note: Except for nested classes, which are described later.

3. Use keywords. this and. New
The inner class gets a reference to the current perimeter class object, and you can use the. This keyword to note the difference from new

Java code
private int num;  Public Test2 () {        } public    Test2 (int num) {      this.num = num;  }    Private class inner{public      Test2 getTest2 () {          return test2.this;      }            Public Test2 NewTest2 () {          return new Test2 ();      }  }    public static void Main (String [] args) {      Test2 test = new Test2 (5);      Test2.inner Inner = Test.new Inner ();      Test2 test2 = Inner.gettest2 ();      Test2 test3 = Inner.newtest2 ();      System.out.println (test2.num);      System.out.println (Test3.num);  }  

Output is 5 0
When you use. This, you get a reference to the perimeter class object that was used when the inner class was created, and new is the one that created the reference.

The. New keyword
You can use the. New keyword if you want to create an inner class object directly, rather than by means of a perimeter class object.
The form is like this:

Java code
Outclass.innerclass obj = outclassinstance.new innerclass ();  


Must be a perimeter class object. New, not a perimeter class. New

Java code
public class First {public  class contents{public      void F () {          System.out.println ("in class first ' s inner class Contents method F () ");      public void Getstr () {          System.out.println ("first.str=" +str);      }  }    public static void Main (String [] args) {First First      = new first ();      First.contents Contents = First.new Contents ();      CONTENTS.F ();  }      }     


You must create an inner class object by using the object first of the outer class first
It is also important to note that it is not possible to create an object of an inner class (except nested classes) before creating a perimeter class object.
4. Internal class and upward transformation
When you move an inner class up to a base type, especially an interface, the inner class comes into play.

Java code
Public interface Shape {public  void paint ();      }      public class Painter {               private class Innershape implements shape{public      void Paint () {          System.out.println (" Painter Paint () method ");      }  }    Public Shape Getshape () {      return new Innershape ();  }                  public static void Main (String []args) {      Painter Painter = new Painter ();      Shape shape = painter. Getshape ();      Shape.paint ();  }      }  


At this point, the inner class is private, it can be outside the class painter, no one can access.
In this way, the private inner class provides a way for tired designers to completely block any type-dependent encoding and completely hide the implementation details.

5. The class within the method
You can create a class within a method.

Java code
public void Test () {  inner{public   Void Method () {  ystem.out.println ("class created within a method");}  }  


It is important to note that the class created within the method cannot have access modifiers.
Also, the classes inside the method are not created when the method is called, and they are compiled as well (how do you know?). will be explained later).

6. Anonymous Inner class

Java code
  public class Painter {  ublic shape Getshape () {  return new shape () {public      void paint ()          { System.out.println ("Painter Paint () method");      }  ;          public static void Main (String [] args) {              Painter Painter = new Painter ();              Shape shape = painter.getshape ();              Shape.paint ();        }    }    Public interface Shape {  ublic void paint ();    }  


Note that the semicolon behind the anonymous inner class is indispensable!
Anonymous class, as the name implies, is no name.
In the Getshape () method, an anonymous inner class is used.
Looks strange, does not conform to the traditional wording?
At first glance it does look like this.

This writing means creating an object that implements the anonymous class of shape.
Anonymous classes can be created, interfaces, abstract classes, and objects with ordinary classes. When you create an interface, you must implement all the methods in the interface.

This is not a parameter, what if you need parameters?
can be transmitted directly.

Java code
public class B {public  A geta (int num) {      return new A (num) {                };  }     }     public class A {  private int num;  public A (int num) {      this.num = num;  }  Public A () {        }     }     


Ok, in this example, you can pass in a parameter to the constructor of a. In the anonymous inner class, this parameter is not used.
If this parameter is used, then this parameter must be final.

Java code
   public class B {public  A geta (final int num) {      return new A (num) {public         int getnum () {                       return num;                    }      };  }     }     public class A {  private int num;  public A (int num) {      this.num = num;  }  Public A () {        }     }     


If it is not final, the compiler will prompt an error.
In addition, you can define attributes in an anonymous inner class
Because the class is anonymous, there is no constructor, and if you want to mimic the constructor, you can initialize the instance ({})

Java code
Public a Geta () {  return new A () {      int num = 0;      String str;      {          str = "Javaeye";          System.out.println ("Hello Robbin");}}  ;     }     


Anonymous inner classes are initialized by instance to achieve the effect of similar constructors ~

The factory method can also be modified by anonymous internal classes.

Java code
  Public interface Service {public void method1 ();    } public interface Servicefactory {Service getService (); } public class Implemention1 implements service{public void Method1 () {System.out.println (' in Implemention1 meth  OD method1 () "); } public static Servicefactory factory = new Servicefactory () {public Service GetService () {return new Im      Plemention1 ();    }  }; } public class Implemention2 implements Service {public void method1 () {System.out.println ("in Implemention2 met  Hod method1 () "); } public static Servicefactory factory = new Servicefactory () {public Service GetService () {return new Im      Plemention2 ();      }  };      public class Test {public static void main (String []args) {service (implemention1.factory);            Service (implemention2.factory);      Servicefactory factory1 = implemention1.factory;      Service Service1 = Factory1.getservice ();            Service1.method1 (); ServicefactorY Factory2 = implemention1.factory;      Service Service2 = Factory2.getservice ();  Service2.method1 ();   }    }


In Implemention1 and 2 the anonymous inner class is used in the field initialization place.
Is the factory method defined so that the code does not look elegant?

7. Nested classes
The inner class of static is called a nested class
As mentioned many times before, nested classes are an exception
There are two points to note when using nested classes:
A, when creating nested class objects, you do not need a perimeter class
b, in a nested class, you cannot access a non-static member of a perimeter class like a normal inner class

Java code
public class Staticclass {  private int num;  private static int sum = 2;  private static class staticinnerclass{public      int Getnum () {      //can only access sum, cannot access num                 return sum;}}    } Public    class Test {public  static void Main (String [] args) {                 //can create nested class objects      directly from new Staticclass.staticinnerclass inner = new Staticclass.staticinnerclass ();      Inner.getnum ();  }    }  


In addition, nested classes have a special place in which you can have static methods in nested classes, static fields and nested classes, which cannot be found in ordinary inner classes.

8. Internal class identifier
We know that each class produces a. class file, and the file name is the class name
Similarly, an inner class produces such a. class file, but its name is not the class name of the inner class, but it has strict restrictions: the name of the perimeter class, plus $, plus the inner class name.
The inner class defined in the method above is not generated when the method is called, but is compiled with the perimeter class, and can be demonstrated by looking at the. class file.

9. Why internal classes?
A, the inner class provides some kind of window into the Periphery class.
b, and the most compelling reason, each inner class can inherit an interface independently, regardless of whether the peripheral class has inherited an interface.
Therefore, the inner class makes the solution for multiple inheritance more complete.
In a project, multiple inheritance is required, and if it is two interfaces, then the interface supports multiple inheritance.
What if it's a two class? Only the inner class is used.

Java code
  Public interface One {public  void Inone ();     }     Public interface-{public  void Intwo ();     }     Two interfaces, the common class can be implemented multiple inheritance public     class Commonclass implements One,two {public  void Inone () {      System.out.println ("Commonclass inone () method");    public void Intwo () {      System.out.println ("Commonclass intwo () method");  }     }     Public abstract class Three {public  abstract void Inthree ();     }     Public abstract class Four {public  abstract void Infour ();     }     Two abstract classes, using the ordinary class cannot implement multiple inheritance          //using inner classes can implement public class     Contents extends three {public  void Inthree () {      System.out.println ("in Contents inthress () method");  }    public class Innerfour extends four{public      void Infour () {          System.out.println (' in Contents ');      }        }     }     


In addition, there are many places where you can use inner classes. Read the Hibernate source code of the classmate, you should be able to find that there are many internal classes.
The most common internal class, it should be map.entry, you can look at the source code ~

Summarize:
The characteristics of the inner class are basically the above, the characteristics are very intuitive, after understanding, the use is very simple.
However, when to use what I say is not very clear, because I have limited knowledge, the use of internal classes is not a lot. The project is seldom used, as if it were activemq there.
However, I believe that we understand the characteristics of the inner class, and then over time, slowly accumulate experience, should make their own judgments, when the use of internal classes, how to apply.

Java Internal class

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.