Home Java javaTutorial Advanced Class Design using Java Sealed Classes

Advanced Class Design using Java Sealed Classes

Nov 03, 2024 am 01:51 AM

Advanced Class Design using Java Sealed Classes

Introduction

In object-oriented programming, class design plays a crucial role in creating robust and maintainable code. With the release of Java 15, a new feature called sealed classes has been introduced, adding an extra layer of control and security to class design. Sealed classes allow developers to restrict class hierarchies, preventing external classes from extending or implementing them. In this article, we will discuss the concept of sealed classes, their benefits, and how they can be implemented in Java.

What are sealed classes?

A sealed class is a new type of class introduced in Java 15, that restricts the inheritance and implementation of its subclasses. It can be considered as a sealed container that allows only specific classes to extend or implement it. Once a class is declared as sealed, it becomes final by default, and any attempt to extend or implement it by external classes will result in a compilation error.

Advantages of using sealed classes

1. Enhanced Security: Sealed classes provide an additional layer of security by restricting the inheritance and implementation of its subclasses. This prevents the unauthorized modification of core classes and ensures that only trusted subclasses can access and modify the sealed class.

2. Better Control over Class Hierarchies: With sealed classes, developers have better control over the class hierarchies. By explicitly defining the allowed subclasses, we can ensure that only relevant and properly designed classes extend or implement the sealed class, leading to a more maintainable codebase.

3. Improved Code Flexibility: By restricting the subclasses that can extend or implement a sealed class, we can make necessary changes or refactoring without worrying about breaking any external code. This provides a sense of flexibility while working with sealed classes and ensures that the codebase remains stable and maintainable.

Implementation of Sealed Classes

To declare a class as sealed, we can use the 'sealed' keyword in the class declaration as shown below:

//Sealed class declaration
public sealed class Triangle permits EquilateralTriangle, RightAngleTriangle {

    //Class body
}
Copy after login
Copy after login

Here, the 'permits' keyword is used to specify the subclasses that are allowed to extend the sealed class. In the above example, only the classes 'EquilateralTriangle' and 'RightAngleTriangle' can extend the 'Triangle' class.

Now, let's create the subclasses that can extend the 'Triangle' class.

//Example of Subclass that Extends Sealed Class
public final class EquilateralTriangle extends Triangle {
    //Class body
}

//Example of Subclass that Extends Sealed Class
public non-sealed class RightAngleTriangle extends Triangle {
    //Class body
}
Copy after login
Copy after login

Notice that the 'EquilateralTriangle' class is declared as 'final' since it is the last subclass in the inheritance hierarchy, and the 'RightAngleTriangle' class is declared as 'non-sealed' since it allows further subclasses to extend it.

Next, let's see an example of implementing sealed interfaces. An interface can be declared as sealed using the same syntax as sealed classes.

//Sealed class declaration
public sealed class Triangle permits EquilateralTriangle, RightAngleTriangle {

    //Class body
}
Copy after login
Copy after login

Here, the 'permits' keyword is used to specify the classes that are allowed to implement the sealed interface. In the above example, only the classes 'Rectangle' and 'Circle' can implement the 'Shape' interface.

//Example of Subclass that Extends Sealed Class
public final class EquilateralTriangle extends Triangle {
    //Class body
}

//Example of Subclass that Extends Sealed Class
public non-sealed class RightAngleTriangle extends Triangle {
    //Class body
}
Copy after login
Copy after login

Notice that the 'Rectangle' class is declared as 'final' since it is the last class to implement the 'Shape' interface, and the 'Circle' class is declared as 'non-sealed' since it allows further classes to implement it.

Inheritance rules for sealed classes and interfaces

  1. A sealed class must explicitly permit the subclasses that can extend it.
  2. All the permitted subclasses must be direct subclasses of the sealed class. This means that we cannot extend a non-permitted subclass to create an indirect subclass of the sealed class.
  3. A sealed interface must explicitly permit the classes that can implement it.
  4. All the permitted classes must implement all the interface methods. This means that we cannot create a class that partially implements the sealed interface.

Conclusion

Sealed classes are a powerful addition to Java that can greatly enhance class design and make the codebase more secure and maintainable. By restricting the hierarchy of classes and interfaces, sealed classes provide an additional layer of control and flexibility while designing classes. With this new feature, developers can ensure that only trusted subclasses or implementing classes can access and modify the sealed class, leading to a more stable and robust codebase. Enhance your Java skills by taking latest Java Certifications.

The above is the detailed content of Advanced Class Design using Java Sealed Classes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles