Site icon TestingDocs.com

What is the difference between Sealed classes and Abstract classes in Java

Introduction

Sealed classes are new in JDK 15.Sealed classes are used to seal the class inheritance hierarchy to certain known child classes. An abstract class is used for an abstract concept or unknown implementations and behavior for the class.

Abstract class

An abstract class is a class that is declared as abstract. It may or may not contain abstract methods. An abstract method is a method that has no implementation. An abstract class cannot be instantiated. Any number of classes can extend the abstract class.

Note that the Preview Features are experimental features and might change in the future versions of JDK. Execute caution when enabling these features in production environments.

Sealed Class

A sealed class restricts other child classes that extend the class. The permits clause is used to specify the child classes. The child classes of the sealed class can be

A sealed class is in preview mode from JDK15. Sealed classes can also be abstract.

 

 

Many classes can extend an abstract class. Only the permitted classes can extend the Sealed Class. The child classes of Sealed Class can only be final or sealed or non-sealed.

Exit mobile version