Comprehensive understanding of internal classes and anonymous classes in Java _java

Source: Internet
Author: User
Tags anonymous inheritance

Java Internal class (Inner Class), similar concepts in C + +, that is, nested classes (Nested Class), at first glance the inner class seems superfluous, its usefulness for beginners may not be so significant, but with its in-depth understanding, You will find that the Java designer is really well-intentioned in the inner class. Learning to use internal classes is part of Mastering Java Advanced Programming, which allows you to design your program structure more gracefully. The following are described in the following ways:

First time to meet

 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, class content and gdestination are defined within the class goods, and each has protected and private modifiers to control the access level. Content represents the contents of goods, and gdestination represents the destination of goods. They implement two interface content and destination respectively. In the main method that follows, you use contents C and destination D directly, and you don't even see the names of these two inner classes! In this way, the first benefit of the inner class is reflected--hiding what you don't want others to know, or encapsulation.

At the same time, we have discovered that the first way to get an inner class object outside the scope of the outside class is to create and return it using the methods of its external classes. This is done by the Cont () and Dest () methods in the previous example. So is there any other way? Of course, its grammatical format is as follows:

Outerobject=new Outerclass (constructor Parameters);

Outerclass.innerclass innerobject=outerobject.new Innerclass (constructor Parameters);

Note When you create a Non-static inner class object, you must first create the corresponding external class object. As for the reason, it leads us to the next topic-

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

To make a slight amendment to the example just now:

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 ();
  }
}

The modified section is shown in red. Here we add a private member variable valuerate to the goods class, meaning that the value factor of the goods is multiplied by the value of the method value () of the internal class content. We find that value () can access valuerate, which is also the second benefit of the inner class--An internal class object can access the contents of the external class object that created it, even the private variable! This is a very useful feature that provides us with more ideas and shortcuts in design. To implement this functionality, an inner class object must have a reference to an external class object. When the Java compiler creates an internal class object, it implicitly passes the reference to its outer class object and keeps it in place. This allows the inner class object to always be able to access its external class object, and this is why outside classes are scoped to create an internal class object that must first create its outer class object.

One might ask if a member variable in an inner class has the same name as a member variable of an outer class, or a member variable with the same name as the outer class is blocked, what should I do? It's okay, Java. The reference to the external class is expressed in the following format:

Outerclass.this

With it, we are not afraid of this shielding situation.

Static Inner class

As with ordinary classes, inner classes can also have static. However, as opposed to non-static inner classes, the difference is that static inner classes do not have references to external ones. This is actually very much like the nested classes in C + +, and the biggest difference between Java internal classes and C + + nested classes is whether there is a reference to the outside, and of course there are differences from the design point of view and some details.

In addition, in any non-static inner class, there can be no static data, static methods, or another static inner class (The inner class 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 within a method or even a block of code.

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 of this. In method Dest we define an inner class, and finally this method returns the object of the inner class. If we use an inner class just to create an object of it and create it externally, we can do so. Of course, the internal classes defined in the method can diversify the design, not just at this point.

Here's a more bizarre 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 an object of this inner class outside of if, because it is beyond its scope. At compile time, however, the inner class Trackingslip is compiled at the same time as the other classes, except that it is invalidated by its own scope and beyond this scope, except that it is not different from other internal classes.

Anonymous inner class

The syntax rules for the anonymous inner class of Java look odd, but like an anonymous array, when you just need to create a class object and can't use its name, using an inner class makes the code look neat and clear. Its grammatical rules are this:

New InterfaceName () {...}; or new Superclassname () {...};

Let's go ahead with the example:

public class Goods3 {public
   Contents cont () {return
     new Contents () {
        private int i = one;
        public int value () {return
          i;}}
     ;
}}

Here the Method cont () Returns an object of the class that implements the interface contents directly using the anonymous inner class, which looks really neat.

Anonymous internal classes are used in a large number of anonymous adapters in Java event handling. For example, when you want to close a window, add a code like this:

Frame.addwindowlistener (New Windowadapter () {public
   void windowclosing (WindowEvent e) {
     system.exit (0);
   }
});

One thing to be aware of is that an anonymous inner class does not have a constructor because it has no name (but if the anonymous inner class inherits a parent class that contains only the parameter constructor, you must take these parameters when you create it, and call the corresponding content with the Super keyword during implementation). If you want to initialize its member variables, there are several ways:

If you are in the anonymous inner class of a method, you can use this method to pass in the parameters you want, but remember that these parameters must be declared final.

The anonymous inner class is changed to a local inner class with a name so that it can have a constructor.

Use the initialization code block in this anonymous inner class.

Why do I need an inner class?

What are the benefits of a Java internal class? Why do I need an inner class?

Let's start with a simple example, if you want to implement an interface, but one of the methods in this interface and the name of a method in the class you are thinking about, what should you do? At this point, you can build an inner class to implement this interface. Because all of the content of the inner class external classes is accessible, this completes all the functionality that you can implement directly on this interface.

But you may have to question it, would you please change the method?

Indeed, the reason for designing the inner class is not convincing.

The real reason for this is that the internal classes and interfaces in Java are added together to solve a problem that is often complained of by C + + programmers in Java--there is no more inheritance. In fact, the multiple inheritance of C + + design is very complex, and Java through the internal class plus interface, can be very good to achieve the effect of multiple inheritance.

Java Internal class summary

(1) non-static inner classes defined between methods:

The perimeter class and the inner class can access each other's own private members.

Static member variables cannot be defined in an inner class.

Outer class scope outward to create an inner class object must first create its outer class object

(2) Static internal classes defined between methods:

Only static members of external classes can be accessed.

Static inner class has no reference to external

(3) The local inner class defined in the method:

The inner class does not have any access control permissions

The outer class cannot see the local inner class in the method, but the local inner class can access any member of the outer class.

The local inner class can be accessed in the method body, but the access statement must be after the local inner class is defined.

A local inner class can only access constants in the method body, that is, a member that is final decorated.

(4) Anonymous inner class defined in the method:

Without a constructor, instead passing the constructor parameter to the Superclass builder

When you just need to create a class object and can't use its name, using an anonymous inner class can make the code look neat and clear.

The above comprehensive understanding of Java in the internal class and anonymous class is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.