Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of making an inner class as static with Java?

I have an inner class in my Java class.

enter image description here

When I run find bugs, it recommends(warns) to make it as static.

enter image description here

What's the point of this warning? What's the advantage of making a inner class as static?

like image 768
prosseek Avatar asked Apr 22 '13 12:04

prosseek


People also ask

What is the advantage of static inner class in Java?

The advantage of a static nested class is that it doesn't need an object of the containing class to work. This can help you to reduce the number of objects your application creates at runtime. It's called a nested class. All nested classes are implicitly static; if they are not static they are called inner classes.

Why do we make inner class static?

Static Nested Class : can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.

Do Java inner classes have to be static?

Terminology: Nested classes are divided into two categories: non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class.

What are the advantages and disadvantages of inner classes?

Inner classes are used to develop a more readable and maintainable code because they logically group classes and interfaces in one place. Easy access, as the inner object, is implicitly available inside an outer Code optimization requires less code to write. It can avoid having a separate class.


2 Answers

If the nested class does not access any of the variables of the enclosing class, it can be made static. The advantage of this is that you do not need an enclosing instance of the outer class to use the nested class.

like image 50
Jeff Storey Avatar answered Oct 08 '22 18:10

Jeff Storey


An inner class, by default, has an implicit reference to an object of the outer class. If you instantiate an object of this from the code of the outer class, this is all done for you. If you do otherwise you need to provide the object yourself.

A static inner class does not have this.

That means it can be instantiated outside the scope of an outer class object. It also means that if you 'export' an instance of the inner class, it will not prevent the current object to be collected.

As a basic rule, if the inner class has no reason to access the outer one, you should make it static by default.

like image 43
Joeri Hendrickx Avatar answered Oct 08 '22 19:10

Joeri Hendrickx