Sealed Classes and Sealed Interfaces Enhancements (Java 17)

 Sealed Classes and Sealed Interfaces Enhancements (Java 17)


Java 17 introduced enhancements to sealed classes and sealed interfaces, providing more control and flexibility in defining the inheritance hierarchy. These enhancements include the ability to:

Declare a permitted subclass or subinterface as non-sealed, allowing it to be further extended by other classes or interfaces.

Declare a permitted subclass or subinterface as final, preventing further subclassing or subinterface extension.

Declare a sealed class or sealed interface in a different package than its permitted subclasses or subinterfaces.

These enhancements allow for more fine-grained control over the inheritance hierarchy, promoting better encapsulation and extensibility.


Here's an example:



// In package com.example

public sealed class Shape permits Circle, Rectangle {

    // Common shape properties and methods

}


public final class Circle extends Shape {

    // Circle-specific properties and methods

}


// In package com.example.shapes

public non-sealed class Square extends Shape {

    // Square-specific properties and methods

}


// In package com.example.shapes.triangle

public final class EquilateralTriangle extends Shape {

    // EquilateralTriangle-specific properties and methods

}

In this example, the Shape class is sealed and permits subclasses Circle and Rectangle. The Square class, located in a different package, is declared as non-sealed, allowing further subclasses. The EquilateralTriangle class is a final subclass of Shape, demonstrating that a permitted subclass can be declared as final.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...