Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example:
public abstract class A {}
public final class B extends A {}
public final class C extends A {}
public final class D extends A {}
Can I somehow enforce that no other subclasses of A can ever be created?
Java is an object-oriented language, and doesn't support algebraic data types directly. We have two ways to simulate the type. Because an algebraic data type exposes the data structure, we may use a class with public fields to simulate an algebraic data type.
The Sealed classes and Record classes provide sum and product types for Java. These algebraic data types are great and they provide a cleaner way to pattern match. The pattern matching provides concise, readable code, and exhaustive type checks by the compiler.
Pattern matching!
Give class A
a constructor with package-level accessibility (and no other constructors).
Thanks, Dave L., for the bit about no other constructors.
You probably want an enum (Java >= 1.5). An enum type can have a set of fixed values. And it has all the goodies of a class: they can have fields and properties, and can make them implement an interface. An enum cannot be extended.
Example:
enum A {
B,
C,
D;
public int someField;
public void someMethod() {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With