Why should I use an internal class in Java?

Source: Internet
Author: User
Document directory
  •  
1. Internal class

First, let's take a simple example. If you want to implement an interface, but a method in this interface has the same name and parameter as a method in the class you have conceived, what should you do? In this case, you can create an internal class to implement this interface. Since all the content of the internal class is accessible to external departments, this can achieve all the functions you directly implement this interface.
But you may have to question it. Isn't it enough to change the method?
Indeed, there is no persuasion to use this as a reason for designing internal classes.
The real reason is that the internal classes and interfaces in java can be combined to solve a problem that C ++ programmers often complain about in java-there is not much inheritance. In fact, the multi-inheritance design of c ++ is very complicated, and java can implement multi-inheritance effectively by adding interfaces to internal classes.
Internal class: the definition of an internal class is defined in another internal class.
The reason is:
1. An internal class object can access the implementation of the object created for it, including private data.
2. For other classes in the same package, internal classes can be hidden.
3. Anonymous internal classes can easily define callbacks.
4. Use internal classes to easily write event drivers

Internal classes allow you to design your program structure more elegantly. The following describes how:

First meeting
public interface Contents { int value();}public interface Destination { String readLabel();}

 

public class Goods { private class Content implements Contents {   private int i = 11;  public int value() {   return i;  }  } protected class GDestination implements Destination {   private String label;  private GDestination(String whereTo) {    label = whereTo;  }  public String readLabel() {   return label;  } } public Destination dest(String s) {   return new GDestination(s); } public Contents cont() {   return new Content(); }}class TestGoods { public static void main(String[] args) {  Goods p = new Goods();   Contents c = p.cont();  Destination d = p.dest("Beijing");    }}

In this example
Content and gdestination
It is defined in the goods class and has
Protected and private
Modifier to control the access level. Content represents
Goods content, while gdestination
Represents the destination of goods. They implement the content and destination interfaces respectively. In the following main method, use
Contents C and
Destination D. You don't even see the names of these two internal classes! In this way,The first benefit of the internal class is embodied-hiding the operations you don't want others to know, that is, encapsulation.

At the same time, we also found that the first method to get internal class objects out of the scope of the external class is to create and return the internal class objects using its external class method. Cont () and
This is what the Dest () method does. Is there any other way? Of course, the syntax format is as follows:

outerObject=new outerClass(Constructor Parameters);outerClass.innerClass innerObject=outerObject.new InnerClass(Constructor Parameters);

Note that when creating a non-static internal class object, you must first create an external class object. The reason leads to our next topic --

Non-static internal class objects have references to their external class objects.

Modify the example above

public class Goods {  private valueRate=2; private class Content implements Contents {   private int i = 11 * valueRate;  public int value() {   return i;  } } protected class GDestination implements Destination {  private String label;  private GDestination(String whereTo) {   label = whereTo;  }  public String readLabel() {   return label;  } } public Destination dest(String s) {  return new GDestination(s); }  public Contents cont() {  return new Content(); }}

Here we give
The goods class adds a private
The member variable valuerate indicates the value coefficient of the goods, including
Content Method
Value () is used to multiply the value. We found that value ()
You can access valueRate, which is alsoThe second benefit of the internal class-an internal class object can access the content of the external class object created for it, and even include private variables!This is a very useful feature that provides us with more ideas and shortcuts during design. To implement this function, internal class objects must have references pointing to external class objects. Java
When the compiler creates an internal class object, it implicitly transfers the reference of its external Class Object and keeps saving it. In this way, internal class objects can always access their external class objects. This is also the reason why they must first create their external class objects to create an internal Class Object outside the scope of the external class. (See http://blog.csdn.net/yu422560654/article/details/6978981 for specific reasons)

Someone may ask, what if a member variable in the internal class has the same name as a member variable in the external class, that is, the member variable with the same name in the external class is blocked? Nothing. Java uses the following format to express external class references:
OuterClass. this
With it, we are not afraid of such blocking.

 

Static internal class (nested class)

Like normal classes, internal classes can also be static. However, compared with non-static internal classes, the difference is that static internal classes do not point to external references. This actually corresponds
The Nested classes in C ++ are very similar.
The biggest difference between an internal class and a C ++ nested class is whether there is a reference pointing to an external class. Of course, there are differences from the design perspective and some details.
In addition, no non-static internal class can have static data, static methods, or another static internal class (internal class nesting can be more than one layer ). However, static internal classes can have all of this. This is the second difference between the two.

 

Local internal class

Yes, Java
Internal classes can also be local, which can be defined in a method or even a code block.

public class Goods1 { public Destination dest(String s) {  class GDestination implements Destination {   private String label;   private GDestination(String whereTo) {    label = whereTo;   }    public String readLabel() { return label; }  }  return new GDestination(s); } public static void main(String[] args) {   Goods1 g= new Goods1();  Destination d = g.dest("Beijing"); }}

The above is an example. In the dest method, we define an internal class. Finally, this method returns the object of this internal class. If we only need to create an object of an internal class and pass it to the external class, we can do this. Of course, the internal class defined in the method can diversify the design, and its purpose is not only in this regard.

The following is a more strange example:

public class Goods2{ 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("slip");   String s = ts.getSlip();  } }  public void track() { internalTracking(true); } public static void main(String[] args) {  Goods2 g= new Goods2();  g.track();  }}

You cannot
Create the object of this internal class outside if because it is beyond its scope. However, during compilation, internal classes
TrackingSlip is compiled at the same time as other classes, but it is in its own scope. It is invalid if it exceeds this scope, and it is no different from other internal classes.

 

2. Anonymous class

Anonymous classes cannot have names, so they cannot be referenced. They must be declared as part of the new statement at creation.

This requires another new statement, as shown below:

New <class or interface> <class subject>

In this form, the new statement declares a new anonymous class, which extends a given class or implements a given interface. He also creates a new instance of that class and returns it as the result of the statement. The class to be extended and the interface to be implemented are:
The operand of the new statement, followed by the subject of the anonymous class.

If an anonymous class is extended to another class, its subject can be a member of the class, override his method, and so on, which is the same as any other standard class. If an anonymous class implements an interface, its subject must implement the interface method.

Note that the declaration of anonymous classes is implemented at compilation and instantiation is performed at runtime. This means
A new statement in the for loop creates several instances of the same Anonymous class, instead of creating several instances of different anonymous classes.

Technically, anonymous classes can be considered non-static internal class, so they have the same permissions and restrictions as non-static internal classes declared in the method.

Assume that the task needs an object, but it is not worth creating a new object (probably because the required class is too simple or because it is only used within a method ), anonymous classes are very useful. Anonymous classes are especially suitable for quickly creating event handlers in Swing applications.

interface pr {  void print1(); }public class noNameClass {  public pr dest() {   return new pr() {     public void print1() {     System.out.println("Hello world!!");     }   }; }}public static void main(String args[]) {   noNameClass c = new noNameClass(); pr hw = c.dest();  hw.print1();}

One thing to note is that the anonymous internal class has no name, so it does not have a constructor (but if this anonymous internal class inherits a parent class that only contains a parameter constructor, these parameters must be included during creation and used during the implementation process.
The super keyword calls the corresponding content ). If you want to initialize its member variables, you can use the following methods:
1. If you are using an anonymous internal class of a method, you can use this method to pass in the desired parameters, but remember that these parameters must be declared
Final.
2. Transform the anonymous internal class into a local internal class with a name, so that it can have constructor.
3. Use the initialization code block in this anonymous internal 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.