1

I know the meaning of nested static classes, but found it confusing sometimes deciding when to declare them over non static nested classes.

Is it mainly when instantiation wouldn't be a good sense?

What are the general rules of thumb helping you decide when to use static modifier?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nimrod
  • 1,100
  • 1
  • 11
  • 27

4 Answers4

3

This is a very interesting question. I would try to explain it to you.

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Basically, a static nested class interacts with the instance members of its top-level class, just like any other classes.

So, basically you can and should consider a static nested class as a top-level class which has been nested inside another top-level class just for packaging convenience.

So whenever you are using a nested class, start by making it static, and then see if you need to access any instance members thereby having an opportunity to make it non-static.

Take the example from JDK,

public class LinkedList<E> ... {
...

 private static class Entry<E> { ... }

}

Here, the Entry is a static nested class as it doesn't make any sense for this class to be a top-level class as it is used by the LinkedList class only. And since it doesn't even use any members of the LinkedList class, thus making is static makes even more sense.

Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
2

always use static. if you need to access members from the outer class use non static

Edit: a good explanation can be found here https://sonar.spring.io/coding_rules#rule_key=squid%3AS2694|s=createdAt|asc=false

Soccertrash
  • 1,830
  • 3
  • 28
  • 48
0

You should use the static field, method or class when ever you can and the code still compiles and works correctly.

If the code wouldn't compile or not work if you made it static, don't make it static.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You'd use a static class when you don't want the class to access non-static (or instance) fields of the top-level class and the top-level class doesn't need an instance of it.

Always use a static inner class unless you can't use a non-static class. This keeps the code simpler and it's more memory efficient.

Luke Melaia
  • 1,470
  • 14
  • 22