search
HomeJavajavaTutorialAdvanced Class Design using Java Sealed Classes

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
}

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
}

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
}

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
}

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
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
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment