Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the java anonymous inner class

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use java anonymous inner classes". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First, use anonymous inner classes

The anonymous inner class does not have a name, so it is created in a somewhat strange way. The format is as follows:

New parent class constructor (parameter list) | implementation API ()

{

/ / the body part of the anonymous inner class

}

Here we see that with anonymous inner classes we have to inherit a parent class or implement an interface, and of course we can only inherit a parent class or implement an interface. It also has no class keyword, because anonymous inner classes directly use new to generate a reference to an object. Of course, this reference is implicit.

Public abstract class Bird {

Private String name

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

Public abstract int fly ()

}

Public class Test {

Public void test (Bird bird) {

System.out.println (bird.getName ()) + "can fly"

+ bird.fly () + "meter")

}

Public static void main (String [] args) {

Test test = new Test ()

Test.test (new Bird () {

Public int fly () {

Return 10000

}

Public String getName () {

Return "wild goose"

}

});

}

}-Output: geese can fly 10000 meters

In the Test class, the test () method accepts a parameter of type Bird, and we know that there is no way to new an abstract class directly. We must have an implementation class before we can new its implementation class instance. So use the anonymous inner class directly in the mian method to create an Bird instance.

Because an anonymous inner class cannot be an abstract class, it must implement all abstract methods in its abstract parent class or interface.

This anonymous inner class code can actually be split into the following forms:

Public class WildGoose extends Bird {

Public int fly () {

Return 10000

}

Public String getName () {

Return "wild goose"

}

}

WildGoose wildGoose = new WildGoose ()

Test.test (wildGoose)

Here the system creates an object that inherits from the anonymous class of the Bird class, which is transformed into a reference to the Bird type.

There is a defect in the use of an anonymous inner class, that is, it can only be used once. When an anonymous inner class is created, it will immediately create an instance of the class, and the definition of the class will disappear immediately. So anonymous inner classes can not be reused. For the above example, if we need to use the inner class in the test () method multiple times, it is recommended to redefine the class instead of using an anonymous inner class.

II. Points for attention

When using anonymous inner classes, we need to pay attention to the following points:

1. When using anonymous inner classes, we must inherit a class or implement an interface, but we cannot have both. At the same time, we can only inherit a class or implement an interface.

2. Constructors cannot be defined in anonymous inner classes.

3. There cannot be any static member variables and static methods in anonymous inner classes.

4. The anonymous inner class is a local inner class, so all restrictions of the local inner class also apply to the anonymous inner class.

5. An anonymous inner class cannot be abstract, it must implement all abstract methods of an inherited class or implemented interface.

3. Why should the parameter used be final

When we pass a parameter to an anonymous inner class, the parameter must be final if it needs to be used in the inner class. That is to say, when the parameter of the method needs to be used in the inner class, the parameter must be final.

Why does it have to be final?

First of all, we know that after the inner class is compiled successfully, it produces a class file, which is not the same class file as the external class, and only retains references to the external class. When the parameters passed in by the external class need to be called by the inner class, it is called directly from the point of view of the java program:

Public class OuterClass {

Public void display (final String name,String age) {

Class InnerClass {

Void display () {

System.out.println (name)

}

}

}

}

From the above code, it seems that the name parameter should be called directly by the inner class. In fact, after java compilation, the actual operation is as follows:

Public class OuterClass$InnerClass {

Public InnerClass (String name,String age) {

This.InnerClass$name = name

This.InnerClass$age = age

}

Public void display () {

System.out.println (this.InnerClass$name +)

"- -" + this.InnerClass$age)

}

}

So from the above code, the inner class is not the parameter passed by the calling method directly, but uses its own constructor to back up the incoming parameters. the internal method calls are actually their own properties rather than the parameters passed by the external method.

Until now, why final has not been explained here? From the outside, the properties in the inner class and the parameters of the external method are the same thing, but in fact they are not, so they can be changed arbitrarily, that is to say, my changes to the properties in the inner class will not affect the external parameters, but this is not feasible from the programmer's point of view, after all, from the program's point of view, the two are basically the same, if the inner class should be changed. However, the parameter of the external method does not change, which is difficult to understand and unacceptable, so in order to maintain the consistency of the parameters, it is stipulated to use final to avoid the parameter does not change.

The simple understanding is that to copy a reference, in order to avoid changing the value of the reference, such as being modified by the methods of the external class, and resulting in inconsistent values obtained by the internal class, use final to make the reference immutable.

So if you define an anonymous inner class and want it to use an externally defined parameter, the compiler will require that the parameter reference be final.

IV. Anonymous inner class initialization

We usually use constructors to initialize an instance, but anonymous inner classes don't have constructors! So how do you initialize anonymous inner classes? Use the construction code block! The effect of creating a constructor for anonymous inner classes can be achieved by using the construction code block.

Public class OutClass {

Public InnerClass getInnerClass (final int age,final String name) {

Return new InnerClass () {

Int age_

String name_

/ / construct the code block to complete the initialization {

If (0 < age & & age < 200) {

Age_ = age

Name_ = name

}

}

Public String getName () {

Return name_

}

Public int getAge () {

Return age_

}

}

}

Public static void main (String [] args) {

OutClass out = new OutClass ()

InnerClass inner_1 = out.getInnerClass (201, "chenssy")

System.out.println (inner_1.getName ())

InnerClass inner_2 = out.getInnerClass (23, "chenssy")

System.out.println (inner_2.getName ())

}

}

This is the end of the content of "how to use java anonymous inner classes". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report