Member-only story

Effective Java! Favor Static Members Classes over Non-Static

Kyle Carter
3 min readJan 11, 2021

Java provides four ways to declare a class within another class: static member class, nonstatic member classes, anonymous classes, and local classes. Each type has it’s benefits and it’s downsides so understanding the correct use cases for each type will help us use the right one in our code. Let’s go over each type.

Static member class: This is the simplest of the nested class options. This ends up being basically a regular class that happens to be inside of a different class. It can be retrieved without already having a reference to the enclosing class. These classes are a static member of the enclosing class and obey the same visibility rules as other members of the class. A common use for this type of class is as a helper to the enclosing class. For example let’s consider a Calculator class. Perhaps it would have an Operation nested class that includes a number of constants that define different operations that could be performed in the calculator. These would be accessed as follows Calculator.Operation.PLUS or Calculator.Operation.MINUS. This creates a nice organization for accessing these helper classes. Another place that you will see these static nested classes being used is with the Builder pattern where the builder object is a nested class inside of the class being built.

Nonstatic member class: The only difference between the declaration between a static nested class and a nonstatic nested class is the word static but this one word difference has quite a difference…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet