Java Internal classes

Source: Internet
Author: User

1. Inner class

Let's start with a simple example, if you want to implement an interface, but one of the methods in this interface is the same as the name of a method in the class you're envisioning, and the parameters are the same, what should you do? At this point, you can build an internal class to implement this interface. Since all the contents of the internal class are accessible, doing so can accomplish all of the functions that you directly implement this interface.
But you may have to question, change the method is not OK?
Indeed, it is not convincing to justify the design of internal classes.
The real reason is that the internal classes and interfaces in Java are added together, and the solution is often complained by C + + programmers that there is a problem in Java-there is no more inheritance. In fact, C + + 's multi-inheritance design is very complex, and Java through the internal class plus interface, can be a good implementation of multi-inheritance effect.
Inner class: The definition of an inner class is a class that is defined within another.
The reasons are:
1. An object of an inner class can access the implementation of the object that created it, including private data.
2. For other classes in the same package, inner classes can be hidden.
3. Anonymous inner classes can easily define callbacks.
4. The use of internal classes can be very convenient to write event drivers

The inner class allows you to design your program structure more elegantly. Here are a few of the following:

Meet for the first time [Java]View Plaincopyprint?
    1. Public interface Contents {
    2.  int value ();
    3. }
    4. Public interface Destination {
    5. String Readlabel ();
    6. }


[Java]View Plaincopyprint?
  1. Public class Goods {
  2.  Private class Content implements Contents {
  3. private int i = 11;
  4.   public int Value () {
  5.    return i;
  6. }
  7. }
  8.  Protected class Gdestination implements Destination {
  9. private String label;
  10.   Private Gdestination (String whereto) {
  11. label = Whereto;
  12. }
  13.   Public String Readlabel () {
  14.    return label;
  15. }
  16. }
  17.  Public Destination dest (String s) {
  18. return new Gdestination (s);
  19. }
  20.  Public Contents cont () {
  21. return new Content ();
  22. }
  23. }
  24. Class Testgoods {
  25.  Public static void Main (string[] args) {
  26. Goods p = new Goods ();
  27. Contents C = P.cont ();
  28. Destination d = p.dest ("Beijing");
  29. }
  30. }


In this example, the class Content and gdestination are defined inside the class Goods, and each has protected and private modifiers to control the access level. Content represents the contents of Goods, while Gdestination represents the destination of Goods. They implement two interface content and destination, respectively. In the following main method, you can operate directly with Contents C and Destination D, and you can't even see the names of the two inner classes! In this way, the first benefit of the inner class is manifested-hiding the actions you don't want others to know, or encapsulation.

At the same time, we also discovered that the first method of getting an inner class object outside the scope of the outside class is to create and return using the methods of its outer classes. The Cont () and Dest () methods in the above example do so. So there's no other way? Of course, its syntax is as follows:

[Java]View Plaincopyprint?
    1. outerobject=New Outerclass (Constructor Parameters);
    2. Outerclass.innerclass Innerobject=outerobject.  New Innerclass (Constructor Parameters);

Note When creating a non-static inner class object, be sure to create the appropriate outer class object first. As for the reason, it leads us to the next topic-

A non-static inner class object has a reference to its outer class object

Modify the example above

[Java]View Plaincopyprint?
  1. Public class Goods {
  2. private valuerate=2;
  3.  Private class Content implements Contents {
  4. private int i = one * valuerate;
  5.   public int Value () {
  6.    return i;
  7. }
  8. }
  9.  Protected class Gdestination implements Destination {
  10.   Private String label;
  11.   Private Gdestination (String whereto) {
  12. label = Whereto;
  13. }
  14.   Public String Readlabel () {
  15.    return label;
  16. }
  17. }
  18.  Public Destination dest (String s) {
  19.   return new Gdestination (s);
  20. }
  21. Public Contents cont () {
  22.   return new Content ();
  23. }
  24. }


Here we add a private member variable valuerate to the Goods class, meaning that the value coefficient of the goods, in the inner Content of the method value () to calculate the value when it is multiplied. We find that value () can access valuerate, which is also the second benefit of the inner class--An inner class object can access the contents of the Outer class object that created it, even the private variable! This is a very useful feature that gives us more ideas and shortcuts in design. To implement this function, the inner class object must have a reference to the Outer class object. When the Java compiler creates an inner class object, it implicitly passes in the reference to its outer class object and keeps it. This allows the inner class object to always have access to its outer class object, and this is why the outer class object must first be created when the outer class scope is outward to create an inner class object. (For specific reasons see: http://blog.csdn.net/yu422560654/article/details/6978981)

One would ask, what if a member variable in an inner class has the same name as a member variable of an outer class, or if the member variable of the same name in the outer class is masked? It's okay, Java uses the following format to express references to external classes:
Outerclass.this
With it, we are not afraid of this shielding situation.

Static inner class (nested Class)

As with ordinary classes, internal classes can also have static. However, compared to non-static inner classes, the difference is that the static inner class does not have a reference to the external. This is actually quite similar to the nested class in C + +, where the biggest difference between a Java inner class and a C + + nested class is whether there is a reference to the outside, of course, from the point of view of design and some of its details.
In addition, in any non-static inner class, there can be no static data, static methods, or another static inner class (inner classes may be nested more than one layer). But the static inner class can have it all. This is the second difference between the two.

Local inner class

Yes, the Java inner class can also be local, and it can be defined in a method or even within a block of code.

[Java]View Plaincopyprint?
  1. Public class Goods1 {
  2.  Public Destination dest (String s) {
  3.   Class Gdestination implements Destination {
  4.    Private String label;
  5.    Private Gdestination (String whereto) {
  6. label = Whereto;
  7. }
  8. Public String Readlabel () { return label;}
  9. }
  10.   return new Gdestination (s);
  11. }
  12.  Public static void Main (string[] args) {
  13. GOODS1 g= New Goods1 ();
  14. Destination d = g.dest ("Beijing");
  15. }
  16. }

The above is an example of this. In method Dest we define an inner class, and finally the object of this inner class is returned by this method. If we only need to create one of its objects and pass it to the outside when we use an inner class, we can do so. Of course, the internal classes defined in the method can diversify the design, and the use is not just at this point.

Here's a more bizarre example:

[Java]View Plaincopyprint?
  1. Public class goods2{
  2.  Private void Internaltracking (boolean b) {
  3.   if (b) {
  4.    Class Trackingslip {
  5.     Private String ID;
  6. Trackingslip (String s) {
  7. ID = s;
  8. }
  9. String Getslip () { return ID;}
  10. }
  11. Trackingslip ts = new Trackingslip ("slip");
  12. String s = ts.getslip ();
  13. }
  14. }
  15. public void Track () {internaltracking (true);}
  16.  Public static void Main (string[] args) {
  17. Goods2 g= New Goods2 ();
  18. G.track ();
  19. }
  20. }

You cannot create an object of this inner class outside of if, because it is beyond its scope. However, at compile time, the inner class Trackingslip and other classes are compiled at the same time, except that it is not valid by its own scope, beyond this range, except that it is not different from other internal classes.

2. Anonymous class

Anonymous classes are classes that cannot have names, so there is no way to reference them. They must be declared as part of the new statement at the time of creation.
This will take another form of the new statement, as follows:

New < class or interface > < body of class >

This form of the new statement declares a novel anonymous class that expands on a given class or implements a given interface. He also creates a new instance of that class and returns it as a result of the statement. The class to be extended and the interface to be implemented are operands of the new statement, followed by the body of the anonymous class.
If an anonymous class extends another class, his principal can access the members of the class, overwrite his method, and so on, which is the same as any other standard class. If an anonymous class implements an interface, his principal must implement the method of the interface.

Note that the declaration of an anonymous class occurs at compile time, and the instantiation occurs at run time. This means that a new statement in the For loop creates several instances of the same anonymous class, rather than creating an instance of several different anonymous classes.

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

An anonymous class can be useful if the task you want to perform requires an object, but it is not worth creating a completely new object (either because the desired class is too simplistic or because he is using it only within a single method). Anonymous classes are especially useful for quickly creating event handlers in swing applications.

[Java]View Plaincopyprint?
    1. Interface PR {
    2.  void Print1 ();
    3. }
    4. Public class Nonameclass {
    5.  Public PR dest () {
    6.   Return New Pr () {
    7. public void Print1 () {
    8. System.out.println ("Hello world!!");
    9. }
    10. };
    11. }
    12. }
    13. Public static void Main (String args[]) {
    14. Nonameclass C = new Nonameclass ();
    15. PR HW = c.dest ();
    16. Hw.print1 ();

Java Internal classes

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.