Java Sealed Class Record Example

1. Introduction

In this blog post, we explore the concept of sealed classes in Java and how they can be used with records. Sealed classes, a feature introduced in Java 17, allow developers to define classes that have restricted hierarchies. Combining them with records, which are a form of concise data carriers, results in powerful and expressive class designs.

Definition

Sealed classes restrict which other classes or interfaces may extend or implement them. Records, introduced in Java 16, are a special kind of data class that hold immutable data. When records are used as permitted subclasses in sealed classes, they provide both the benefits of immutability and controlled extension.

2. Program Steps

1. Define a sealed class.

2. Create record classes that are permitted subclasses of the sealed class.

3. Use these records in an application.

3. Code Program

// Sealed class definition
sealed interface Pet permits Cat, Dog {
    String sound();
}

// Record class Cat
record Cat(String name) implements Pet {
    @Override
    public String sound() {
        return name + " says Meow!";
    }
}

// Record class Dog
record Dog(String name) implements Pet {
    @Override
    public String sound() {
        return name + " says Woof!";
    }
}

public class SealedClassRecordExample {
    public static void main(String[] args) {
        Pet cat = new Cat("Whiskers");
        Pet dog = new Dog("Buddy");

        System.out.println(cat.sound());
        System.out.println(dog.sound());
    }
}

Output:

Whiskers says Meow!
Buddy says Woof!

Explanation:

1. The Pet interface is a sealed class, permitting only Cat and Dog as its implementations.

2. Cat and Dog are records implementing the Pet interface. Each overrides the sound method to return a species-specific sound.

3. In the SealedClassRecordExample class, instances of Cat and Dog are created and treated as Pet types.

4. The sound method is called on each instance, demonstrating polymorphism within the sealed class hierarchy.

5. This example illustrates how sealed classes can be effectively used with records in Java to define clear and restricted hierarchies with immutable data.


Comments