Java Sealed Classes and Coupling

489 Views Asked by At

When programming, there are many indicators that coupling is bad. A class should know as little as possible about other classes. So it is modular and can easily be replaced.

Now, with the introduction of sealed classes, the abstract super-class knows about its sub-classes. As I understand it, the sub-classes would normally be in the same package (or even the same file) as their sealed interface. So there should not be a problem of cyclic dependencies between packages.

So I guess what I am asking is: Should a sealed interface and its sub-classes be regarded as one unit, and not as modular parts that are dependent on each other?

Example where the sub-classes are outside the package:

import asdf.Car;
import asdf.Truck;

public sealed interface Service permits Car, Truck {

To trigger-happy close-voters: An implementor of a sealed interface cannot exist outside the interface's module so the answer is pretty cut and dry. Not opinion-based at all. Here is a comment from Brian Goetz that you might be interested in: Sealed classes for classes in different packages

I already got my answer though so I don't really care if no one else can answer. Have a nice day!

1

There are 1 best solutions below

3
On BEST ANSWER

Inheritance is always strong coupling between types; hence most often you should follow

Favor composition over inheritance

Most of the cases when you use inheritance could be resolved with composition and dependency injection.


Keeping subclasses close to the base class inside the one module is a good practice and doing otherwise is not recommended. You don't want to have a strong coupling between not related packages or modules.


There are exceptions to everything I said. F.e You might want to create a library of abstract classes than developers in your project could extend without duplicating utility code. F.ex java collections and abstract collection classes. .