DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Trending

  • Introduction to Error Prone: How to Catch Bugs at Compile Time
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • The Art of Idempotency: Preventing Double Charges and Duplicate Actions
  • Picture Perfect: Choosing Your Featured Image

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Effectively Sealed Classes in Java

Effectively Sealed Classes in Java

Sealed classes are extremely helpful in class implementation in Java. Check out this post on using sealed classes and the Option class in Java.

By 
Grzegorz Piwowarek
·
Aug. 16, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
28.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Java is missing various “hot” features from languages like Scala or Kotlin, but luckily some of them can be recreated using existing features — sealed hierarchies are one of these.

In this short article, we’ll see how to achieve the “sealed” effect by playing around with Java.

Sealed Classes

One of the most popular sealed hierarchies that exist is Option. The classic implementation involves making Option a sealed abstract class and providing two subclasses: Some  and None .

In Scala, it looks like:

sealed abstract class Option[+A] extends Product {}

case object None extends Option[Nothing] {}
case class Some[+A](value: A) extends Option[A] {}


If we try to further extend Option, it’s no longer possible as long as we can’t add the extension to the file with the base class — and that’s the essence of class sealing.

Furthermore, we could leverage additional compiler support, for example, when working with pattern matching.

You can find more examples in Kotlin, as well.

Sealed Classes in Java

Since we don’t have a dedicated solution, we need to try to construct our own.

In Java, Optional is implemented in a totally different way, because it’s designed to become a value type in the future — but that’s another story for another time.

But, now, let’s try to achieve sealed-class semantics using Vanilla Java. The whole trick relies on a clever usage of visibility restrictions of private constructors and nested classes:

public abstract class Option<T> {
    // ...
    public final static class Some<T> extends Option<T> { ... }
    public final static class None<T> extends Option<T> { ... }
}


Unfortunately, we can’t really forbid the class from being extended. However, we can make every extension outside the file unusable by making the default constructor private:

public abstract class Option<T> {
    private Option() {}
    // ...
    public final static class Some<T> extends Option<T> { ... }
    public final static class None<T> extends Option<T> { ... }
}


And, now, if we try to create an anonymous implementation, we end up with a compilation error:

Option<Integer> o = new Option<Integer>() {}
// 'Option()' has private access in 'com.pivovarit.sealed.Option'



And, if we try to create a standalone extension, it turns out that the default constructor isn’t visible from the outside:

public class SomeNone<T> extends Option<T> {
    private SomeNone() {
    }
}
// There is no default constructor available in 'com.pivovarit.sealed.Option'


And this is how we end up with an effectively sealed class in Java.


A Complete Example

package com.pivovarit.sealed;

import java.util.function.Supplier;

public abstract class Option<T> {

    abstract T getOrElse(Supplier<T> other);

    private Option() {
    }

    public final static class Some<T> extends Option<T> {

        private final T value;

        public Some(T value) {
            this.value = value;
        }

        @Override
        T getOrElse(Supplier<T> other) {
            return value;
        }
    }

    public final static class None<T> extends Option<T> {
        @Override
        T getOrElse(Supplier<T> other) {
            return other.get();
        }
    }
}


The above code snippet can be found on GitHub.

Java (programming language)

Published at DZone with permission of Grzegorz Piwowarek. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook