views:

217

answers:

3

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?

+2  A: 

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

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

Mark Cidade
Alternatively all as nested classes with A having a private constructor only.
Tom Hawtin - tackline
That's not as aesthetic, though: A.B, A.C...
Mark Cidade
import static to the rescue, marxidad
Apocalisp
Wouldn't anyone be able to copy the package name, and put their own class in that package that extends A?
MetroidFan2002
+1  A: 

You could put class A,B,C,D in a seperate package and make class A not public.

Jan Gressmann
Making class A private sort of defeats the purpose of algebraic datatypes (i.e., polymorphism)
Mark Cidade
+2  A: 

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


}
asterite
If I'm not mistaken, in your example, B, C, and D are values, not types.
Apocalisp
Ah, you're right... you can't create many B's :-(
asterite
But it is good if you don't want the subtypes to have state (in the example they don't even implement any methods).
Tom Hawtin - tackline