Is there a way to implement algebraic types in Java?
-
05-07-2019 - |
Question
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?
Solution 4
Church encoding to the rescue:
public abstract class A {
public abstract <R> R fold(R b, R c, R d);
}
There are only three implementations possible:
public final class B extends A {
public <R> R fold(R b, R c, R d) {
return b;
}
}
public final class C extends A {
public <R> R fold(R b, R c, R d) {
return c;
}
}
public final class D extends A {
public <R> R fold(R b, R c, R d) {
return d;
}
}
OTHER TIPS
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() {
}
}
You could put class A,B,C,D in a seperate package and make class A not public.