Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to implement algebraic types in Java?

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?

like image 965
Apocalisp Avatar asked Oct 04 '08 03:10

Apocalisp


People also ask

Does Java have algebraic data types?

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.

Does Java have sum types?

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.

Does C# have algebraic datatypes?

Pattern matching!


2 Answers

Give class A a constructor with package-level accessibility (and no other constructors).

Thanks, Dave L., for the bit about no other constructors.

like image 115
Mark Cidade Avatar answered Oct 14 '22 16:10

Mark Cidade


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() {
  }


}
like image 38
asterite Avatar answered Oct 14 '22 17:10

asterite