-1

I just have a quick question as I couldn't find any concrete answers on the web. Does having a private static inner class promote loose or tight coupling between it and the outer class in Java?

Thanks for your help in advance, appreciate it!!

KeithNolo
  • 21
  • 1
  • 2
    Does this answer your question? [Why prefer non-static inner classes over static ones?](https://softwareengineering.stackexchange.com/questions/238782/why-prefer-non-static-inner-classes-over-static-ones) – Rik D Nov 06 '20 at 12:23
  • 3
    The truth is, while a nested class can see the private members of the containing class, the coupling level is really *up to you*, i.e., it depends on how you design the interaction between the two. Coupling is not bad in itself, it's unwanted/uncontrolled coupling that we want to avoid, and a private static nested class is usually fairly coupled to its outer class *by design*. What this kind of setup promotes is looser coupling of the outer class with *other* top-level classes, as the one class that needs access to its private members is nested and hidden from the outside world. – Filip Milovanović Nov 06 '20 at 14:11

1 Answers1

4

Having a private static inner class permits tight coupling between it and the outer class in Java. It also permits loose coupling. Why? Because coupling requires more than access.

However, it should be understood that loose coupling isn't always the goal. Oh sure it provides flexibility when achieved but that comes with a cost. There are excellent designs that greatly couple inner and outer classes.

One of my favorites is Joshua Blochs Builder Pattern. Tons of coupling but it simplifies construction by simulating named parameters in a language that lacks them. Yes, it's a pain to add new fields but you get fluent construction and an immutable object out of the deal. Also, by sticking the two highly coupled classes together in the same file it makes it easier to manage the coupling.

So please understand. Just because code has been separated into two classes doesn't mean those two classes have to treat each other like strangers. There are many different kinds of valid relationships between classes.

candied_orange
  • 102,279
  • 24
  • 197
  • 315