Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of having public static inner classes of an interface/class?

Tags:

java

I've noticed the following code pattern while browsing through some sources of my project's 3rd party libraries:

public interface MyInterface {     public static class MyClass1 implements MyInterface { ... }     public static class MyClass2 implements MyInterface { ... }     public static class MyClass3 implements MyInterface { ... } } 

Or this one:

public class MyBaseClass {     public static class MyClass1 extends MyBaseClass { ... }     public static class MyClass2 extends MyBaseClass { ... }     public static class MyClass3 extends MyBaseClass { ... } } 

Real life examples:

  • SwingX: org.jdesktop.swingx.decorator.HighlightPredicate (Source)
  • Substance: org.pushingpixels.substance.api.renderers.SubstanceDefaultTableCellRenderer (Source)

What's the advantage of having a code structure like this?

My first thought was "aggregation", but the same thing could be achieved using plain old packages. So when/why is it better to use public inner classes instead of a package?

like image 486
Daniel Rikowski Avatar asked Mar 22 '11 12:03

Daniel Rikowski


2 Answers

I think this is reasoned by aggregation, maybe they're also not worth it to create a top level class. I do this sometimes if something is to small to create a package (to separate them from others) but the corresponding classes should only used within the context of the top level class. In my opinion this is a design decision.

The decorator pattern may be a nice example, they can be applied on the top-level class but are maybe so simple they're not worth it to be also top-level. You can easily show the ownership by using them as inner classes.

That's not that visible at first glance with packages. You directly see the dependent class/interface.

Further it's possible to access the private fields of a class, this could be useful and is more fine-grained than the package private scope.

like image 150
Christopher Klewes Avatar answered Oct 07 '22 00:10

Christopher Klewes


One use I can think of is to provide ready-made implementations of the interface, publicly available to anyone, but still conceptually tied to the mother interface.

This makes sense only if the interface is simple (thus the inner implementation classes are small), there aren't too many of them, and most of the interface clients actually need them. Otherwise they clutter up the source file, making it harder to understand.

like image 42
Péter Török Avatar answered Oct 06 '22 23:10

Péter Török