Daily tip #9
Tip of the day #9
If you are using JDK 17, delimit your domain using sealed classes and interfaces. Making visible which classes can inherit your code can help your coworkers understand the business framework and make better questions when they need to change it.
Bônus:
you can use sealed interfaces and records (tip from yesterday) together.
More info:
Sealed Classes were proposed by JEP 360 and delivered in JDK 15 as a preview feature. There was a second preview in JDK 16, and now it is a standard feature in JDK 17.
Goals
- Allow the author of a class or interface to control which code is responsible for implementing it.
- Provide a more declarative way than access modifiers to restrict the use of a superclass.
- Support future directions in pattern matching by providing a foundation for the exhaustive analysis of patterns.
But why use inheritance?
Imagine our Vehicle example.
public interface Vehicle {
String getName();
String getColor();
}
public class Car implements Vehicle {
}
public class Motorcycle implements Vehicle {
}
public class Truck implements Vehicle {
}
Nothing stops you from creating a new class that implements Vehicle, but it is not a Car, Motorcycle, or Truck, right?
Now using sealed classes:
public sealed interface Vehicle permits Car, Motorcycle, Truck {
String getName();
String getColor();
}
If you try to declare a new class that implements Vehicle, you will get a compile error.
public class Airplane implements Vehicle {
}
java: class is not allowed to extend sealed interface: Vehicle ( as it is not listed in permits clause of sealed interface)
How to use it
Take a look in repo-tip-9 to see a real example of today’s tip. Try to create the Airplane class and see what happens.