[introduction to Java] Day9 Java internal class – static internal class

Today, let's talk about the last internal class in Java - static internal class

The so-called static inner class is naturally an inner class modified with static. What's special about the inner class modified with static compared with ordinary inner classes?

First, it is static, which means that its creation does not depend on external classes. To create an instance of an internal class, you do not need to create an external class instance like an ordinary internal class.

Secondly, there are advantages and disadvantages. It can't access the methods and member variables of external classes as unrestricted as ordinary internal classes. It can only access static member variables and static methods.

Without much to say, let's take a look at chestnuts:

The output is as follows:

It seems that the use of the internal class is similar to that of the external class. It is more like a class temporarily existing in the external class. It has no essential connection with the external class, but outer. Is required when creating Inner is defined in the same way as adding a namespace to a class.

Take another chestnut to see the difference between static internal classes and non static internal classes: (I think the metaphor is more vivid)

If the class is compared to an egg, the inner class is an egg, and the outer class is an eggshell. Then the static class is equivalent to a cooked egg. Even if the eggshell is broken (the external class is not instantiated), the egg yolk is still intact (the internal class can be instantiated); while the non static class is equivalent to a raw egg. If the eggshell is broken (no instantiation), the egg yolk will follow XX (no instantiation).

As for the reason? In fact, because the pointer of the external class is saved in the non static internal class, you can access all the properties of the external class without restriction, while the static internal class does not. Therefore, the static internal class cannot access the non static members and methods of the external class, just borrow its shell.

Another Chestnut:

Here, getmaxmin needs to return two values at a time, so a pair class is used to bind the two numbers together. Because this class is only used in the calculate class and there is no dependency between the two, it is most appropriate to use a static internal class here.

There are many applicable scenarios for static internal classes, which you need to experience slowly in the future.

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
分享
二维码
< <上一篇
下一篇>>