开发者

Java: Why internal class has to be static?

开发者 https://www.devze.com 2023-02-25 10:46 出处:网络
I know that internal class has to be static because will 开发者_开发问答link between public and internal classes and internal class will be created all times that created public classes.

I know that internal class has to be static because will 开发者_开发问答link between public and internal classes and internal class will be created all times that created public classes. And my question how to check it? I mean write some simple application and make some loop for creating objects and see that objects do not deleted by GC in some profiler, Can I to do something like that nad some one done it? Thanks.


internal class will be created all times that created public classes

If you mean that an instance of the inner class will always be created when you create an instance of the outer class, that is not true.

You can have outer instances with no attached inner instances, and the same outer instance can have any number of attached inner instances (and of different inner classes, too).

It is (somewhat) the opposite rather: When you create an instance of the (non-static) inner class, that instance will contain a reference to its outer instance (but that is a reference to an already existing object, not a new one: You cannot create the inner instance without having the outer one first).


This can be done using static analysis. If you are using Eclipse check out the FindBugs plugin, it can detect the lack of static inner classes and a bunch of other useful problems.


An internal class does not have to be static. In fact, one of their most common manifestations - anonymous inner classes - are never static.

The phrase "static class" does not cause a class to get created at runtime - classes are only "created" once, by the classloader, when they are loaded. What you meant to say is that the instance of the internal class will be created every time an instance of the outer class is created. And this too is false in general (see Thilo's answer).

Don't worry - I misunderstood internal classes in exactly the same way as you when I first learned about them!

A non-static inner class will have an implicit (i.e. it's there automatically, you don't declare it) reference to the instance of the outer class which created it. This will prevent the instance of the outer class being GCed as long as the instance of the inner class exists, just like a normal Java reference.

A static internal class will not have such a reference, because it is not created by an outer instance but by the classloader.

0

精彩评论

暂无评论...
验证码 换一张
取 消