Site icon TestingDocs.com

What is a Sealed Interface in Java

Overview

Sealed Interface allows only the permitted classes to implement the interface. Unknown classes are not allowed to implement the interface. The sealed interface specifies the permitted classes using the permits clause. We can specify the interface as sealed using the keyword sealed.

Sealed Interface

//www.TestingDocs.com
public sealed interface Thinkable permits Person  {
    public void think();
}

 

Only the Person class is allowed to implement the Thinkable interface. Person class can be final, or sealed or non-sealed.

 

 

Person class

package jdk15;
//www.TestingDocs.com
public non-sealed class Person implements Thinkable {
    protected String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void think() {
        System.out.println( getName() + " is thinking...");
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

 

Interfaces in permits clause

Till now we only talked about specifying classes in the permits clause. We can even specify interfaces in the permits clause of a sealed interface.

 

//www.TestingDocs.com
public sealed interface Thinkable permits Dreamable, Person  {
    public void think();
}

 

 

//www.TestingDocs.com
public non-sealed interface Dreamable extends Thinkable {
    public void dream();
}

implements and permits clause

//www.TestingDocs.com
public sealed class Person implements Thinkable, Dreamable permits Employee {
    protected String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public void think() {
        System.out.println( getName() + " is thinking...");
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    public void dream() {
        System.out.println( getName() + " is in REM Sleep...");
    }
}

 

Exit mobile version