Java Learning Notes: A comprehensive introduction to internal classes/anonymous inner classes

Source: Internet
Author: User

When writing a Java program, a class (or interface) is typically placed in a separate Java file, and the class name is the same as the file name (if the class is public, the class name must be the same as the file name; non-public, no mandatory requirement). If you want to put multiple Java classes in a Java file, you can have only one public class. If the following two classes are placed in the same file will be an error, cannot compile through.

As can be seen, because the Testone.java file already has a public class testone, then add a public class Testtwo error. If you remove the public modifier from the front of the class testtwo, there is no problem.

We introduce the concept and use of inner classes, the so-called inner classes, simply put, that is, a class is defined inside another class. Unlike the above two classes in the same file (Testone and Testtwo, although in a file, but not nested with each other, are tied).

The use of internal classes sometimes poses a problem with the readability of the code, but it is necessary in many scenarios. Especially in the use of frameworks (such as the Java Swing, sorting operations in the collection framework), the use of internal classes (especially anonymous inner classes) can bring a lot of convenience, such as when we develop Android apps, we will use a lot of internal classes, if you do not understand the meaning of the inner class and the use of rules, It's almost impossible to develop Android apps smoothly.

The inner class has its special place, one of which is that the inner class instance can access all members of the outer class that contains it, including the private member. It is also important to note that the use of an inner class must be bound to an instance of an external class, which is illustrated in the following example.

Inner classes are also divided into several situations, as explained below hit.

First, the general internal class

Example 1:testtwo is an inner class that can directly access private member A in an external class.

public class Testone {private int a = 2;public static void Main (string[] args) {new Testone (). Call ();} public void Call () {testtwo-n = new Testtwo (); Two.show ();} Class Testtwo {public void Show () {System.out.println (a);}}}

Example 2: If you need to use an inner class in a static method of an external class, you must create an instance of an external class that is used by the new inner class. cannot be directly new, otherwise a compilation error will be reported.

public class Testone {private int a = 2;public static void Main (string[] args) {Testone testone = new Testone (); Testtwo testtwo = Testone.new testtwo (); Testtwo.show ();} public void Call () {testtwo-n = new Testtwo (); Two.show ();} Class Testtwo {public void Show () {System.out.println (a);}}}

Example 3: How to reference an instance of an external class in an inner class. There are two methods, one is the normal method, in the new inner class, the external class's this as the inner class constructor parameters to the inner class, there is an easier way, directly in the inner class through the "External class class name. This" can use an instance of an external class. As in the following code:

public class Testone {private int a = 2;public static void Main (string[] args) {new Testone (). Call ();} public void Call () {new Testtwo (this). Show (); Class Testtwo {private Testone one;public testtwo (Testone one) {this.one = one;} public void Show () {System.out.println (a); System.out.println (ONE.A); System.out.println (TESTONE.THIS.A);}}}

In these cases, an inner class is used, usually the inner class is only used by the outer class, which can hide the inner class and bind to the outer class more tightly.

Ii. internal classes within the method

Is that the inner class is defined inside a method. In this case, the inner class can be used only within the method, and the inner class may access the members of the outer class, but note that the local variables (including parameters) of the method that contains it cannot be accessed unless the variable (or parameter) inside the method is final. Example:

public class Testone {private int a = 2;public static void Main (string[] args) {new Testone (). Call ();} public void Call () {final int b=3;class testtwo {private Testone one;public testtwo (Testone one) {this.one = one;} public void Show () {System.out.println (a); System.out.println (ONE.A); System.out.println (TESTONE.THIS.A); System.out.println (b);}} New Testtwo (This). Show ();}}

It is important to note that if an inner class is defined in a static method, the inner class can only use static members of the outer class.

Third, anonymous internal class

Anonymous internal classes, in fact, there are a lot of situations. The most common scenario is to create an instance of a subclass directly from a parent class, such as an abstract class, or to create an object directly from an interface, which can be passed as a parameter to a method or assigned to a variable. In fact, in the use of internal classes, anonymous classes are the most widely used.

Because we all know that in Java, in general, unlike C + +, we can pass or reference a method as a variable.

We can only pass and reference Java objects. For example, we define a method, a parameter is an interface type or an abstract class, so we do not use anonymous inner class, we need to define a class to implement the interface or abstract class each time, and then create an instance of the class to pass to the method. When the number of methods that need to be implemented in an interface or abstract class is relatively few (for example, only 1), this first creates a class, and then uses it to be more verbose. And in this scenario, the classes that are often created are used in this one place. With anonymous internal classes, you can make your code a lot simpler to write. In fact, some of the APIs provided by Java itself (such as multithreading, Io, collection framework, etc.) are heavily used in this feature. Let's look at a few examples:

Example 1: Creating an object from an interface

public class Testthread {public static void main (string[] args) {Testthread testthread = new Testthread (); TESTTHREAD.FUN1 ( ); Testthread.fun2 ();} public void Fun1 () {Runnable Runnable = new Runnable () {@Overridepublic void run () {System.out.println ("fun1");}}; New Thread (runnable). Start ();} public void Fun2 () {New Thread (new Runnable () {@Overridepublic void run () {System.out.println ("fun2");}}). Start ();}}

As you can see, the object is created directly through the Runnable interface in method fun1 for use by the thread class. fun2 more simplified, the direct hyphen variable name is also omitted, and the creation of the object is created directly when the parameter is passed in.

Example 2: Creating a Subclass object for a parent class directly

public class Testchild {public static void main (string[] args) {new Thread () {@Overridepublic void run () {System.out.print ln ("Thread is Run");}}. Start ();}}

As you can see, the thread class has a run method, but the Run method is empty, and if we want to implement multi-threading with the inherited thread class, we must overload the Run method in the subclass. The above code does not actually show the definition of a thread subclass, but instead creates a threading instance directly from the above form and starts it.

Iv. static nested class (inner Class)

That is, a static class is defined in a class (note that it cannot be defined in a method). differs from the inner class described earlier. This nested class is just a namespace restriction in an external class. In essence, it does not need to be bound to an instance of an external class, or to access an instance member of an external class, only to the static members of an external class. Code such as:

public class Testone {private int a = 2;static private int b = 2;public static void Main (string[] args) {Testtwo testtwo = New Testtwo ();} public void Call () {Testtwo testtwo = new Testtwo ();} Static class Testtwo {public void Show () {System.out.println (b);}}} Class Testthree{public static void Main (string[] args) {testone.testtwo testtwo = new Testone.testtwo ();} public void Call () {Testone.testtwo testtwo = new Testone.testtwo ();}}

As you can see, the use of testtwo does not need to rely on an instance of an external class testone.

The above describes the internal class of several cases, the use of a little attention can be.

Java Learning Notes: A comprehensive introduction to internal classes/anonymous inner classes

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.