Inner class and anonymous class

Source: Internet
Author: User

Inner classes and anonymous classes in Java
* Why do I need an internal class?

What are the benefits of Java internal classes? Why do I need an internal 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, in Java, the internal classes and interfaces together, can be resolved often by C + + programmers complain about a problem in Java?? 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. It is very convenient to write event drivers using an internal class.

1. Inner class

Mentioning the Java inner class (Inner Class) may be a lot of people are not familiar with, in fact, similar concepts in C + +, that is, nested classes (Nested Class), the difference between the two and the connection, there will be a comparison in the following. The inner class, on the surface, is defined in the class as a class (as seen in the following, the inner class can be defined in many places), but in fact it is not so simple, at first glance the inner class seems redundant, its usefulness may not be so significant for beginners, but with a deep understanding of it, You will find that the Java designers are really very diligent in their inner classes. Learning to use internal classes is part of mastering Java's advanced programming, which allows you to design your program structure more elegantly. Here are a few of the following:

* Meet for the first time

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, 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 reflected?? Hide the actions you don't want others to know, that is, 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:
Outerobject=new Outerclass (Constructor Parameters);
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 also leads us to the next topic??

* Non-static inner class object has a reference to its outer class object
Make a few changes to the example just now:

public class Goods {
Private valuerate=2;

Private class Content implements Contents {
private int i = one * 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 part is shown in blue. 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 external class object that created it, even including private variables! 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.
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
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.

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 the object of this inner class is returned by this method. If we only need to create an object of its own and create an external one 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:

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. 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 code:

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


The PR can also be a class, but the method you call externally must be declared in your class or interface, and external methods cannot be called inside the anonymous class.

Perhaps the most common use of anonymous classes in Java is to add Listner to the Frame.
Java code:

Import java.awt.*;
Import java.awt.event.*;

public class Qframe extends Frame {
Public Qframe () {
This.settitle (\ "My application\");

Addwindowlistener (New Windowadapter () {
public void windowclosing (WindowEvent e) {
Dispose ();
System.exit (0);
}
});

This.setbounds (10,10,200,200);
}
}


An internal anonymous class is an internal class that is built without naming you, that is, a variable that has no reference to the instance.

New Windowadapter () {
public void windowclosing (WindowEvent e) {
Dispose ();
System.exit (0);
}
}

New is to create a Windowadapter object, and the following {} indicates that the action in this parenthesis acts on this default pair of names, and the upper Java program is followed by a function body.
The purpose of this usage is to create an instance of an object and override one of its functions.
Open the Windowadapter code to discover. It is an abstract class. It is an implementation of the WindowListener interface.
Frame.addwindowlistner (); The argument is a windowlistner, and the implementation is an anonymous class derived from Windowadapter.

One thing to note is that the anonymous inner class does not have a constructor because it does not have a name, but if the anonymous inner class inherits a parent class that contains only a parameter constructor, it must be created with these parameters, and the corresponding content is invoked using the Super keyword during implementation. If you want to initialize its member variables, there are several ways:
1. If it is an anonymous inner class in a method, you can use this method to pass in the arguments you want, but remember that these parameters must be declared final.
2. Change the anonymous inner class into a named local inner class so that it can have constructors.
3. Use the initialization code block in this anonymous inner class.

Inner class and Anonymous class (GO)

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.