[introduction to Java] Day7 Java internal classes – local internal classes

Today we introduce the second inner class, the local inner class.

What are local inner classes? As the name suggests, it is a class defined within a local (escape). Jokingly, a local internal class is a class defined within a code block, method body, and scope (a piece of code enclosed by curly brackets "{}"). A local internal class has the following characteristics:

For example, chestnuts:

The Inner2 class here is only used in the print method of outer2, and the valid range is only within the print function.

Through this toy code, you may not understand why there are so many restrictions and complex things in Java. Let's take a look at the previous Chestnut: callbacks in Java

Copy the code here:

Here, when we want to create a timer, we need to pass in an object that implements the actionlistener interface, and this object is only used in this method once. At this time, the advantages of the internal class are reflected. The class is encapsulated in the method without providing any redundant information to the external world:

You may feel that it's just like simply moving the class to another class, which is of no Luan use.

On the surface, it is true, but in fact, there are still many luans.

There is a saying in think in Java: the most attractive reason for using internal classes is that each internal class can independently inherit an implementation (Interface), so whether or not the peripheral class has inherited an implementation (Interface) has no impact on the internal class.

As we all know, multi inheritance cannot be implemented in Java, and the interface is the scheme given to supplement and improve multi inheritance. Sometimes there are some problems that are difficult to solve using interfaces in our programming. At this time, we can use the ability provided by internal classes to inherit multiple concrete or abstract classes to solve these programming problems. It can be said that the interface only solves some problems, and the internal class makes the solution of multiple inheritance more complete.

According to personal experience, local internal classes are not very practical, but not commonly used does not mean they are useless. Knowing that there is such a magical internal class, after understanding its characteristics, you can provide more solutions for your future needs.

So far, the explanation of this article is completed. Welcome to continue your attention!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>