7

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?

Don Kirkby
  • 53,582
  • 27
  • 205
  • 286
Apocalisp
  • 34,834
  • 8
  • 106
  • 155

4 Answers4

4

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
  • 98,437
  • 31
  • 224
  • 236
3

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
  • 7,761
  • 2
  • 23
  • 18
  • If I'm not mistaken, in your example, B, C, and D are values, not types. – Apocalisp Oct 04 '08 at 03:24
  • 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 Oct 04 '08 at 13:59
  • Tom, my mouse and keyboard hang, once PC resumes from sleep. You may think it is bad -- you cannot control your computer. But it is good if you do not want to! I always liked this kind of logic. Internet is blocked? No problem, you provider defends you from viruses! It would be worthwile if Java would not exist at all (blank grammar). It would prevent you from writing any program. But you may want to. See? Limitation gives an advantage! – Val Aug 28 '12 at 08:24
0

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

Jan Gressmann
  • 5,481
  • 4
  • 32
  • 26
0

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;
  }
}
Apocalisp
  • 34,834
  • 8
  • 106
  • 155