How to create sealed classes in Java

As far as I can tell, no one else seems to have spotted this trick, so I thought I’d share my latest corruption of the Java language:

public class Sealed
private Sealed() { }

public final static class Foo extends Sealed {
public Foo() { }
public final static class Bar extends Sealed { }

What does this code do? It creates a class Sealed which is *not* final, but only has a finite number of subclasses which you determine at compile time (you can make those subclasses themselves extensible if you want, although I declared them final above). No one else can subclass it because they’re not able to call the super constructor as it’s not visible outside of this class.

This entry was posted in programming and tagged on by .

5 thoughts on “How to create sealed classes in Java

  1. hiker

    This actually is a well known trick in the C++ community as the language doesn’t offer sealed classes. Other classes can inherit from such ‘sealed’ class only if they are declared as friends to it. Nice find, though.

  2. David R. MacIver

    Fair enough. It seemed too simple to be original to me, but I hadn’t seen it anywhere and no one else seemed to have heard of it, so I thought I’d post a note. :-)

    (I guess more generally this is the observation that nested classes allow you to create an approximation to C++’s ‘friend’ status)

  3. James Iry

    D’oh! What’s sad is I had accidentally come awefully close to this before because I used it in an elaboration of the old “Java type safe enum pattern” wherein I had not only a collection of unique values, but each value had to have some custom logic. The result was that each enum was an instance of a unique subclass. I had just totally forgotten about it and never thought to generalize it for sealed classes which might have multiple instances. Thanks David!

  4. David R. MacIver

    Well, note that Java enum instances can be made anonymous classes, so you can already add custom logic to enums as long as you don’t need to add custom method signatures as well (but yes, this trick would work if you wanted custom method signatures).

    Glad you like it. :-)

Comments are closed.