Thursday 28 July 2022

Java15: Sealed interfaces

This is continuation to my previous post ‘sealed classes’, I would request you to go through the previous post before reading this.

 

Sealed classes and interfaces specify who can extend or implement this class or interface. A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so.

 

A interface is sealed by applying the sealed modifier to its declaration. For example, the following declaration declare a sealed interface EmployeeService which permits two classes (PermanentEmployeeServiceImpl,TemporaryEmployeeServiceImpl) to implement it.

 

EmployeeService.java

package com.sample.app.interfaces.sealed;

public sealed interface EmployeeService permits PermanentEmployeeServiceImpl,TemporaryEmployeeServiceImpl {

}

 

PermanentEmployeeServiceImpl.java

package com.sample.app.interfaces.sealed;

public final class PermanentEmployeeServiceImpl implements EmployeeService{

}

 

TemporaryEmployeeServiceImpl.java

package com.sample.app.interfaces.sealed;

public final class TemporaryEmployeeServiceImpl implements EmployeeService{

}

 

Where to specify the permit clause, if my interface extends another interfaces?

After any extends clause to specify superinterfaces, the implementing classes and subinterfaces are specified with a permits clause. 

public sealed interface PersonInterface extends Serializable permits PersonImpl, UserImpl{

}

  

References

https://openjdk.org/jeps/360

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment