SlideShare a Scribd company logo
BLOG
Java Feature Spotlight: Sealed Classes
NOVEMBER 23, 2020
Java technologyis known forits regularand frequentreleases,with something new
developers can lookforward to each time. In September2020, itintroduced anotherone of
these exciting newJava features.The release ofJava SE 15 included “sealed classes”(JEP
360)as a previewfeature. Itis a prominentJava feature.This is becausethe introduction of
sealed classes in Java holdsthe solution to a problemJava has had fromits initial 1.0version,
released 25 years ago.
SeeAlso: Looking BackOn 25 Years OfJava: MajorMilestones
EXPERTS CLIENTS HOW IT WORKS
Table ofContents
1. Context
2. Sealed Classes
3. How To Define A Sealed Class

Type and hit enter...
RECENT POSTS
Java Security Vulnerabilities: Case Commentary
What is TornadoVM?
Getting Comfortable With FPGAs
Java Feature Spotlight: Sealed Classes
The New Java Roadmap: What’s In Store For The
Future?
ARCHIVES
December 2020
November 2020
October 2020
September 2020
August 2020
July 2020
June 2020
BECOME AN XPERTI HIRE AN XPERTI

Context
Aswe all know, one ofthefundamentals ofobject-oriented programming is inheritance. Java
programmers have been reusing fields and methods ofexisting classes byinheriting themto
newclasses. Itsavestime and theydon’thavetowritethe code again. Butthings change ifa
developerdoes notwantto allowanyrandomclassto extend his/hercreated class.This
developercan seal a class ifhe/she doesn’twantanyclients ofhis/herlibrarydeclaring any
more primitives. Bysealing a class, Java Developers can nowspecifywhich classes are
allowed to extend, restricting anyotherarbitraryclassfromdoing so.
Sealed Classes
Sealed classes in Java primarilyprovide restrictions in extending subclasses.A sealed class is
abstractbyitself. Itcannotbe instantiated directly. Butitcan have abstractmembers.
Restriction is nota newconceptin Java.We are all aware ofa Java feature called “final
classes.”Ithas alreadybeen offering restricting extension butthe addition ofsealed classes in
Java can be considered a generalization offinality. Restriction primarilyofferstwo advantages:
Developers get better control over the code as he or she can now control all the
implementations, and
The compiler can also better reason about exhaustiveness just like it is done in
switch statements or cast conversion.  
4. Features Offered By Sealed Classes
4.1. · Extensibility And Control
4.2. · Simplification
4.3. · Protection
4.4. · More Accessibility
4.5. · Exhaustiveness
5. Significance Of Sealed Classes
6. Sum And Product Types
7. Conflict With Encapsulation?
8. Sealed Classes And Records
9. Records And Pattern Matching
10. Conclusion
May 2020
April 2020
March 2020
February 2020
CATEGORIES
Articles
Blog
Press Release
Uncategorized
CONNECT & FOLLOW
   
Subscribe to newsletter now!
Your email address..
SUBSCRIBE
CHECK OUR TWEETS
NEWSLETTER
How To Define A Sealed Class
To seal a class,we need to add the sealed modifierto its declaration.Afterthat, a permits
clause is added.This clause specifiesthe classesthatare allowed to be extended. Itmustbe
added afteranyextends and implements clauses.
Belowis averysimple demonstration ofa sealed class in Java.
1. public sealed class Vehicle permits Car, Truck, Motorcycle {...}
2. final class Car extends Vehicle {...}
3. final class Boat extends Vehicle {...}
4. final class Plane extends Vehicle {...}
In the example above, ‘Vehicle’ isthe name ofa sealed class,which specifiesthree permitted
subclasses;Car, Boatand Plane.
There are certain conditionsfordeclaring a sealed classthatmustbefulfilled bythe
subclasses:
1. The subclasses must be in the same package or module as the base class. It is also
possible to define them in the same source file as the base class. In such a
situation, the “permits” clause will not be required.
2. The subclasses must be declared either final, sealed or non-sealed.
The permits listis defined to mention the selected classesthatcan implement‘Vehicle’. In this
case,these classes are ‘Car’, ‘Boat’ and ‘Plane’.A compilation errorwill be received ifanyother
class orinterface attemptsto extend the ‘Vehicle’ class. 
Features Offered By Sealed Classes
· Extensibility And Control
Sealed classes offera newwayto declare all available subclasses ofa class orinterface. It’s a
handyJava feature. Especiallyifa developerwishesto make superclasses accessiblewhile
restricting unintended extensibility. Italso allows classes and interfacesto have more control
overtheirpermitted subtypes.This can be useful formanyapplications including general
domain modelling and forbuilding more secure and stable platformlibraries. 
Whoever said the path to career success is long
and stony never tried Xperti. Excellent career
opportunities for Am… https://t.co/fJdkbHaKHB
   5 DAYS
Enlightened, ambitious, and ready for a great
challenge! Xperti wishes you a joyous Hanukkah
Festival 2020!… https://t.co/Cf9DmnHj6W
   6 DAYS
Excellent opportunities for your technology career,
only with Xperti, America’s community of top 1%
tech talent. Si… https://t.co/EkofL2C0gE
   7 DAYS
@XPERTI1
LATEST POSTS
Java Security
Vulnerabilities: Case
Commentary
DECEMBER 15, 2020
What is TornadoVM?
DECEMBER 10, 2020
Getting Comfortable With
FPGAs
DECEMBER 2, 2020
Java Feature Spotlight:
· Simplification
Anothernoticeable advantage ofintroducing sealed classes in Java isthe simplification of
code. Itgreatlysimplifies code byproviding an option to representthe constraints ofthe
domain. NowJava coders are notrequired to use a defaultsection in a switch ora catch-all
‘else’ blockto avoid getting an unknown type.Additionally, italso seems useful forserialization
ofdata to and fromstructured data formats, like XML. Sealed classes also allowdevelopersto
knowall possible subtypesthatare supported in the given format. (And yes,the subtypes are
nothidden.Thiswill be discussed in detail laterin the article.)
· Protection
Sealed classes can also be used as a layerofadditional protection againstinitialization of
unintended classes during polymorphic deserialization. Polymorphic deserialization has been
one ofthe primarysources ofattacks in such frameworks.Theseframeworks can take
advantage ofthe information ofthe complete setofsubtypes, and in case ofa potential attack,
theycan stop before even trying to load the class.
· More Accessibility
Thetypical process ofcreating a newclass orinterface includes deciding which scope
modifiermustbe used. Itis usuallyverysimple untilthe developers come across a project
where using a defaultscope modifieris notrecommended bythe official style guide.With
sealed classes, developers nowgetbetteraccessibility, using inheritancewith a sealed scope
modifierwhile creating newclasses. In otherwords,with the entryofsealed classes in Java, ifa
developerneedsthe superclassto bewidelyaccessible butnotarbitraryextensible, he/she
has a straightforward solution.
Sealed classes also allowJava libraries’ authorsto decouple accessibilityfromextensibility. It
providesfreedomand flexibilityto developers. Buttheymustuse itlogicallyand notoveruse it.
Forinstance, ‘List’ cannotbe sealed, as users should havethe abilityto create newkinds of
‘Lists’. Itmakes sensefordevelopersto notseal it.
· Exhaustiveness
Sealed classes also carryoutan exhaustive listofpossible subtypes,which can be used by
both programmers and compilers. Forexample, in the defined class above, a compilercan
extensivelyreason aboutthevehicles class (notpossible withoutthis list).This information can
Sealed Classes
NOVEMBER 23, 2020
INSTAGRAM
View on Instagram
CATEGORIES
Articles (1)
Blog (45)
Press Release (1)
Uncategorized (1)
be used bysome othertools aswell. Forinstance,the Javadoc tool liststhe permitted subtypes
in the generated documentation pagefora sealed class.
Significance Of Sealed Classes
Sealed classes rankhighlyamong the otherfeatures released in Java 15. Jonathan Harley, a
Software DevelopmentTeamLeaderprovided an excellentexplanation on Quora abouthow
importantsealed classes can beforJava Developers: “Thefactthatinterfaces, aswell as
classes, can be sealed is importantto understand howdevelopers can usethemto improve
theircode. Until now, ifyou wanted to expose an abstraction tothe restofan application while
keeping the implementation private,youronlychoiceswereto expose an interface (which can
always be extended)oran abstractclasswith a package-private constructorwhich you hope
will indicateto usersthattheyshould notinstantiate itthemselves. Buttherewas nowayto
restricta userfromadding theirconstructorswith differentsignatures oradding theirpackage
with the same name asyours.”
Hefurtherexplained, “Sealed types allowyou to expose a type (interface orclass)to othercode
while still keeping full control ofsubtypes, and theyalso allowyou to keep abstractclasses
completelyprivate…”
Sum And Product Types
The example mentioned earlierin the article makes a statementabouthowa ‘Vehicle’ can only
eitherbe a:
Car
Boat or a
Plane
Itmeansthatthe setof allVehicles is equaltothe setof all Cars, all Boats and all Planes
combined.This iswhysealed classes are also known as “sumtypes.” Becausetheirvalue setis
the sumofthevalue sets ofa fixed listofothertypes. Sumtypes, and sealed classes are new
forJava butnotin the largerscale ofthings.Scala and manyotherhigh-level programming
languages have been using sealed classestoo, aswell as sumtypesforquite sometime.
Conflict With Encapsulation?
Object-oriented modelling has always encouraged developersto keep the implementation of
an abstracttype hidden.
Butthen whyisthis newJava feature contradicting this rule? 
When developers are modelling awell-understood and stable domain, encapsulation can be
neglected because userswill notbe benefitting fromthe application ofencapsulation in this
case. In theworstpossible scenario, itmayeven make itdifficultforclientstoworkwith avery
simple domain.
This does notmean thatencapsulation is a mistake. Itjustmeansthatata higherand complex
level ofprogramming, developers are aware ofthe consequences. Sotheycan makethe callto
go a bitoutoflineto getsomeworkdone.
Sealed Classes And Records
Sealed classesworkwellwith records (JEP384). Record is a relativelynewJava featurethatis
a formofproducttype. Records are a newkind oftype declaration in Java similarto Enum. Itis
a restricted formofclass. Records are implicitlyfinal, so a sealed hierarchywith records is
slightlymore concise.To explain thisfurther,we can extend the previouslymentioned example
using recordsto declarethe subtypes:
1. sealed interface Vehicle permits Car, Boat, Plane {
2. record Car (float speed, string mode) implements Vehicle {...}
3. record Boat (float speed, string mode) implements Vehicle {...}
4. record Plane (float speed, string mode) implements Vehicle {...}
}
This example shows howsumand record (producttypes)worktogether;we can saythata car,
a plane ora boatis defined byits speed and its mode.
In anotherapplication, itcan also be used forselecting which othertypes can bethe
subclasses ofthe sealed class. 
Forexample, simple arithmetic expressionswith records and sealed typeswould be likethe
code mentioned below:
1. sealed interface Arithmetic {...}
2. record MakeConstant (int i) implements Arithmetic {...}
3. record Addition (Arithmetic a, Arithmetic b) implements Arithmetic {...}
4. record Multiplication (Arithmetic a, Arithmetic b) implements Arithmetic
{...}
5. record Negative (Arithmetic e) implements Arithmetic {...}
Herewe havetwo concretetypes: addition and multiplication which hold two subexpressions,
and two concretetypes, MakeConstantand Negativewhich holds one subexpression. Italso
declares a supertypeforarithmetic and capturesthe constraintthatthese are
the only subtypes ofarithmetic.
The combination ofsealed classes and records is also known as “algebraic datatypes”. Records
allowusto express producttypes, and sealed classes allowusto express sumtypes.
Records And Pattern Matching
Both records and sealed types have an association with pattern matching. Records admiteasy
decomposition intotheircomponents, and sealed types providethe compilerwith
exhaustiveness information sothata switch thatcovers allthe subtypes need notprovide a
defaultclause.
A limited formof pattern matching has been previouslyintroduced in Java SE 14which will
hopefullybe extended in thefuture.This initialversion ofJava feature allows Java developers
to usetype patternsin “instanceof.”
Forexample, let’stake a lookatthe code snippetbelow:
1. if (vehicle instanceof Car c) {
2. // compiler has itself cast vehicle to the car and bound it to c
3. System.out.printf("The speed of this car is %d%n", c.speed());
}
Conclusion
Although manyothertoolswere released with sealed classes, itremainsthe mostprominent
Java feature ofthe release.We are still notcertain aboutthefinal representation ofsealed
classes in Java. (Ithas been released as a previewin Java 15). Butsofarsealed classes are
offering awide range ofuses and advantages.Theyproveto be useful as a domain modelling
technique,when developers need to capture an exhaustive setofalternatives in the domain
model. Sealed types become a natural complementto records, astogethertheyformcommon
patterns. Both ofthemwould also be a natural fitfor pattern matching.  Itis obviousthat
sealed classes serve as a quite useful improvementin Java.And,with the overwhelming
JAVA FEATURE SEALED CLASSES SEALED CLASSES IN JAVA  0    
Java Security Vulnerabilities:
Case Commentary
DECEMBER 15, 2020
What is TornadoVM?
DECEMBER 10, 2020
Getting Comfortable With
FPGAs
DECEMBER 2, 2020
responsefromthe Java community,we can expectthata better, more refined version of
sealed classes in Javawill soon be released.
AUTHOR
Shaharyar Lalani
Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design.
He writes and teaches extensively on themes current in the world of web and app development, especially in Java
technology.

Name Email Website
RELATED POSTS
WRITE A COMMENT
PDFmyURL.com - convert URLs, web pages or even full websites to PDF online. Easy API for developers!
Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment.
POST COMMENT
Enter your comment here..
SKILLSETS IN DEMAND
Designers
Developers
Project Managers
Quality Assurance
Business Analysts
QUICK LINKS
Home
Experts
Clients
FAQ's
Privacy Policy
CONNECT
Contact Us
   
Copyright©2020.Allrights reservedbyXperti

More Related Content

What's hot (8)

PDF
Comment soup with a pinch of types, served in a leaky bowl
Pharo
 
PDF
OSGi: Don't let me be Misunderstood
mikaelbarbero
 
PDF
How to Identify Class Comment Types? A Multi-language Approach for Class Com...
Pooja Rani
 
PDF
PhD defense presenation
Pooja Rani
 
PDF
Would Static Analysis Tools Help Developers with Code Reviews?
Sebastiano Panichella
 
PDF
Java design pattern tutorial
Ashoka Vanjare
 
PDF
invokedynamic: Evolution of a Language Feature
DanHeidinga
 
PDF
50+ java interview questions
SynergisticMedia
 
Comment soup with a pinch of types, served in a leaky bowl
Pharo
 
OSGi: Don't let me be Misunderstood
mikaelbarbero
 
How to Identify Class Comment Types? A Multi-language Approach for Class Com...
Pooja Rani
 
PhD defense presenation
Pooja Rani
 
Would Static Analysis Tools Help Developers with Code Reviews?
Sebastiano Panichella
 
Java design pattern tutorial
Ashoka Vanjare
 
invokedynamic: Evolution of a Language Feature
DanHeidinga
 
50+ java interview questions
SynergisticMedia
 

Similar to Java Feature Spotlight: Sealed Classes (20)

PDF
Sealed classes java
Aryan Verma
 
PDF
Advanced Programming _Abstract Classes vs Interfaces (Java)
Professor Lili Saghafi
 
PPTX
Getting the Most From Modern Java
Simon Ritter
 
DOCX
Core java notes with examples
bindur87
 
PPTX
2CPP09 - Encapsulation
Michael Heron
 
PPTX
Session 38 - Core Java (New Features) - Part 1
PawanMM
 
PDF
Java 17
Mutlu Okuducu
 
PPTX
Objects and classes in OO Programming concepts
researchveltech
 
PDF
JAVA 3.1.pdfdhfksuhdfshkvbhdbsjfhbvjdzfhb
KusumitaSahoo1
 
PDF
Exception handling and packages.pdf
Kp Sharma
 
PPT
Java inheritance
Arati Gadgil
 
PPT
Chapter 5 declaring classes & oop
sshhzap
 
PDF
Java introduction
Muthukumaran Subramanian
 
DOCX
Viva file
anupamasingh87
 
PPTX
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
PPTX
Abstract Class and Interface for Java Intoductory course.pptx
DrShamimAlMamun
 
PPTX
Java Generics
DeeptiJava
 
PDF
java-06inheritance
Arjun Shanka
 
PPTX
Chapter 7:Understanding Class Inheritance
It Academy
 
Sealed classes java
Aryan Verma
 
Advanced Programming _Abstract Classes vs Interfaces (Java)
Professor Lili Saghafi
 
Getting the Most From Modern Java
Simon Ritter
 
Core java notes with examples
bindur87
 
2CPP09 - Encapsulation
Michael Heron
 
Session 38 - Core Java (New Features) - Part 1
PawanMM
 
Java 17
Mutlu Okuducu
 
Objects and classes in OO Programming concepts
researchveltech
 
JAVA 3.1.pdfdhfksuhdfshkvbhdbsjfhbvjdzfhb
KusumitaSahoo1
 
Exception handling and packages.pdf
Kp Sharma
 
Java inheritance
Arati Gadgil
 
Chapter 5 declaring classes & oop
sshhzap
 
Java introduction
Muthukumaran Subramanian
 
Viva file
anupamasingh87
 
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
Abstract Class and Interface for Java Intoductory course.pptx
DrShamimAlMamun
 
Java Generics
DeeptiJava
 
java-06inheritance
Arjun Shanka
 
Chapter 7:Understanding Class Inheritance
It Academy
 
Ad

More from Syed Hassan Raza (20)

PDF
Account Reconciliation: A Detailed Guide
Syed Hassan Raza
 
PDF
What Is Gross Margin? Everything You Need To Know
Syed Hassan Raza
 
PDF
GUIDE TO IMPROVING YOUR TEAM’S TECHNOLOGY QUOTIENT (TQ)
Syed Hassan Raza
 
PDF
Microsoft Introduces Python in Excel
Syed Hassan Raza
 
PDF
What Is React Memo? How To Use React Memo?
Syed Hassan Raza
 
PDF
How To Build Forms In React With Reactstrap?
Syed Hassan Raza
 
PDF
Understanding React SetState: Why And How To Use It?
Syed Hassan Raza
 
PDF
10+ Ways To Optimize The Performance In React Apps
Syed Hassan Raza
 
PDF
A Hands-on Guide To The Java Queue Interface
Syed Hassan Raza
 
PDF
How To Implement a Modal Component In React
Syed Hassan Raza
 
PDF
Understanding React useMemo Hook With Example
Syed Hassan Raza
 
PDF
Functional Programming In Python: When And How To Use It?
Syed Hassan Raza
 
PDF
Cloud Engineer Vs. Software Engineer: What’s The Difference
Syed Hassan Raza
 
PDF
10 Remote Onboarding Best Practices You Should Follow In 2023
Syed Hassan Raza
 
PDF
How To Use Python Dataclassses?
Syed Hassan Raza
 
PDF
A Guide To Iterator In Java
Syed Hassan Raza
 
PDF
Find Trusted Tech Talent With Xperti
Syed Hassan Raza
 
PDF
Software ‘Developer’ Or ‘Engineer’: What’s the Difference?
Syed Hassan Raza
 
PDF
Tax Season 2023: All The Tax Deadlines You Need To Know
Syed Hassan Raza
 
PDF
Understanding Rendering In React
Syed Hassan Raza
 
Account Reconciliation: A Detailed Guide
Syed Hassan Raza
 
What Is Gross Margin? Everything You Need To Know
Syed Hassan Raza
 
GUIDE TO IMPROVING YOUR TEAM’S TECHNOLOGY QUOTIENT (TQ)
Syed Hassan Raza
 
Microsoft Introduces Python in Excel
Syed Hassan Raza
 
What Is React Memo? How To Use React Memo?
Syed Hassan Raza
 
How To Build Forms In React With Reactstrap?
Syed Hassan Raza
 
Understanding React SetState: Why And How To Use It?
Syed Hassan Raza
 
10+ Ways To Optimize The Performance In React Apps
Syed Hassan Raza
 
A Hands-on Guide To The Java Queue Interface
Syed Hassan Raza
 
How To Implement a Modal Component In React
Syed Hassan Raza
 
Understanding React useMemo Hook With Example
Syed Hassan Raza
 
Functional Programming In Python: When And How To Use It?
Syed Hassan Raza
 
Cloud Engineer Vs. Software Engineer: What’s The Difference
Syed Hassan Raza
 
10 Remote Onboarding Best Practices You Should Follow In 2023
Syed Hassan Raza
 
How To Use Python Dataclassses?
Syed Hassan Raza
 
A Guide To Iterator In Java
Syed Hassan Raza
 
Find Trusted Tech Talent With Xperti
Syed Hassan Raza
 
Software ‘Developer’ Or ‘Engineer’: What’s the Difference?
Syed Hassan Raza
 
Tax Season 2023: All The Tax Deadlines You Need To Know
Syed Hassan Raza
 
Understanding Rendering In React
Syed Hassan Raza
 
Ad

Recently uploaded (20)

PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 

Java Feature Spotlight: Sealed Classes

  • 1. BLOG Java Feature Spotlight: Sealed Classes NOVEMBER 23, 2020 Java technologyis known forits regularand frequentreleases,with something new developers can lookforward to each time. In September2020, itintroduced anotherone of these exciting newJava features.The release ofJava SE 15 included “sealed classes”(JEP 360)as a previewfeature. Itis a prominentJava feature.This is becausethe introduction of sealed classes in Java holdsthe solution to a problemJava has had fromits initial 1.0version, released 25 years ago. SeeAlso: Looking BackOn 25 Years OfJava: MajorMilestones EXPERTS CLIENTS HOW IT WORKS Table ofContents 1. Context 2. Sealed Classes 3. How To Define A Sealed Class  Type and hit enter... RECENT POSTS Java Security Vulnerabilities: Case Commentary What is TornadoVM? Getting Comfortable With FPGAs Java Feature Spotlight: Sealed Classes The New Java Roadmap: What’s In Store For The Future? ARCHIVES December 2020 November 2020 October 2020 September 2020 August 2020 July 2020 June 2020 BECOME AN XPERTI HIRE AN XPERTI 
  • 2. Context Aswe all know, one ofthefundamentals ofobject-oriented programming is inheritance. Java programmers have been reusing fields and methods ofexisting classes byinheriting themto newclasses. Itsavestime and theydon’thavetowritethe code again. Butthings change ifa developerdoes notwantto allowanyrandomclassto extend his/hercreated class.This developercan seal a class ifhe/she doesn’twantanyclients ofhis/herlibrarydeclaring any more primitives. Bysealing a class, Java Developers can nowspecifywhich classes are allowed to extend, restricting anyotherarbitraryclassfromdoing so. Sealed Classes Sealed classes in Java primarilyprovide restrictions in extending subclasses.A sealed class is abstractbyitself. Itcannotbe instantiated directly. Butitcan have abstractmembers. Restriction is nota newconceptin Java.We are all aware ofa Java feature called “final classes.”Ithas alreadybeen offering restricting extension butthe addition ofsealed classes in Java can be considered a generalization offinality. Restriction primarilyofferstwo advantages: Developers get better control over the code as he or she can now control all the implementations, and The compiler can also better reason about exhaustiveness just like it is done in switch statements or cast conversion.   4. Features Offered By Sealed Classes 4.1. · Extensibility And Control 4.2. · Simplification 4.3. · Protection 4.4. · More Accessibility 4.5. · Exhaustiveness 5. Significance Of Sealed Classes 6. Sum And Product Types 7. Conflict With Encapsulation? 8. Sealed Classes And Records 9. Records And Pattern Matching 10. Conclusion May 2020 April 2020 March 2020 February 2020 CATEGORIES Articles Blog Press Release Uncategorized CONNECT & FOLLOW     Subscribe to newsletter now! Your email address.. SUBSCRIBE CHECK OUR TWEETS NEWSLETTER
  • 3. How To Define A Sealed Class To seal a class,we need to add the sealed modifierto its declaration.Afterthat, a permits clause is added.This clause specifiesthe classesthatare allowed to be extended. Itmustbe added afteranyextends and implements clauses. Belowis averysimple demonstration ofa sealed class in Java. 1. public sealed class Vehicle permits Car, Truck, Motorcycle {...} 2. final class Car extends Vehicle {...} 3. final class Boat extends Vehicle {...} 4. final class Plane extends Vehicle {...} In the example above, ‘Vehicle’ isthe name ofa sealed class,which specifiesthree permitted subclasses;Car, Boatand Plane. There are certain conditionsfordeclaring a sealed classthatmustbefulfilled bythe subclasses: 1. The subclasses must be in the same package or module as the base class. It is also possible to define them in the same source file as the base class. In such a situation, the “permits” clause will not be required. 2. The subclasses must be declared either final, sealed or non-sealed. The permits listis defined to mention the selected classesthatcan implement‘Vehicle’. In this case,these classes are ‘Car’, ‘Boat’ and ‘Plane’.A compilation errorwill be received ifanyother class orinterface attemptsto extend the ‘Vehicle’ class.  Features Offered By Sealed Classes · Extensibility And Control Sealed classes offera newwayto declare all available subclasses ofa class orinterface. It’s a handyJava feature. Especiallyifa developerwishesto make superclasses accessiblewhile restricting unintended extensibility. Italso allows classes and interfacesto have more control overtheirpermitted subtypes.This can be useful formanyapplications including general domain modelling and forbuilding more secure and stable platformlibraries.  Whoever said the path to career success is long and stony never tried Xperti. Excellent career opportunities for Am… https://t.co/fJdkbHaKHB    5 DAYS Enlightened, ambitious, and ready for a great challenge! Xperti wishes you a joyous Hanukkah Festival 2020!… https://t.co/Cf9DmnHj6W    6 DAYS Excellent opportunities for your technology career, only with Xperti, America’s community of top 1% tech talent. Si… https://t.co/EkofL2C0gE    7 DAYS @XPERTI1 LATEST POSTS Java Security Vulnerabilities: Case Commentary DECEMBER 15, 2020 What is TornadoVM? DECEMBER 10, 2020 Getting Comfortable With FPGAs DECEMBER 2, 2020 Java Feature Spotlight:
  • 4. · Simplification Anothernoticeable advantage ofintroducing sealed classes in Java isthe simplification of code. Itgreatlysimplifies code byproviding an option to representthe constraints ofthe domain. NowJava coders are notrequired to use a defaultsection in a switch ora catch-all ‘else’ blockto avoid getting an unknown type.Additionally, italso seems useful forserialization ofdata to and fromstructured data formats, like XML. Sealed classes also allowdevelopersto knowall possible subtypesthatare supported in the given format. (And yes,the subtypes are nothidden.Thiswill be discussed in detail laterin the article.) · Protection Sealed classes can also be used as a layerofadditional protection againstinitialization of unintended classes during polymorphic deserialization. Polymorphic deserialization has been one ofthe primarysources ofattacks in such frameworks.Theseframeworks can take advantage ofthe information ofthe complete setofsubtypes, and in case ofa potential attack, theycan stop before even trying to load the class. · More Accessibility Thetypical process ofcreating a newclass orinterface includes deciding which scope modifiermustbe used. Itis usuallyverysimple untilthe developers come across a project where using a defaultscope modifieris notrecommended bythe official style guide.With sealed classes, developers nowgetbetteraccessibility, using inheritancewith a sealed scope modifierwhile creating newclasses. In otherwords,with the entryofsealed classes in Java, ifa developerneedsthe superclassto bewidelyaccessible butnotarbitraryextensible, he/she has a straightforward solution. Sealed classes also allowJava libraries’ authorsto decouple accessibilityfromextensibility. It providesfreedomand flexibilityto developers. Buttheymustuse itlogicallyand notoveruse it. Forinstance, ‘List’ cannotbe sealed, as users should havethe abilityto create newkinds of ‘Lists’. Itmakes sensefordevelopersto notseal it. · Exhaustiveness Sealed classes also carryoutan exhaustive listofpossible subtypes,which can be used by both programmers and compilers. Forexample, in the defined class above, a compilercan extensivelyreason aboutthevehicles class (notpossible withoutthis list).This information can Sealed Classes NOVEMBER 23, 2020 INSTAGRAM View on Instagram CATEGORIES Articles (1) Blog (45) Press Release (1) Uncategorized (1)
  • 5. be used bysome othertools aswell. Forinstance,the Javadoc tool liststhe permitted subtypes in the generated documentation pagefora sealed class. Significance Of Sealed Classes Sealed classes rankhighlyamong the otherfeatures released in Java 15. Jonathan Harley, a Software DevelopmentTeamLeaderprovided an excellentexplanation on Quora abouthow importantsealed classes can beforJava Developers: “Thefactthatinterfaces, aswell as classes, can be sealed is importantto understand howdevelopers can usethemto improve theircode. Until now, ifyou wanted to expose an abstraction tothe restofan application while keeping the implementation private,youronlychoiceswereto expose an interface (which can always be extended)oran abstractclasswith a package-private constructorwhich you hope will indicateto usersthattheyshould notinstantiate itthemselves. Buttherewas nowayto restricta userfromadding theirconstructorswith differentsignatures oradding theirpackage with the same name asyours.” Hefurtherexplained, “Sealed types allowyou to expose a type (interface orclass)to othercode while still keeping full control ofsubtypes, and theyalso allowyou to keep abstractclasses completelyprivate…” Sum And Product Types The example mentioned earlierin the article makes a statementabouthowa ‘Vehicle’ can only eitherbe a: Car Boat or a Plane Itmeansthatthe setof allVehicles is equaltothe setof all Cars, all Boats and all Planes combined.This iswhysealed classes are also known as “sumtypes.” Becausetheirvalue setis the sumofthevalue sets ofa fixed listofothertypes. Sumtypes, and sealed classes are new forJava butnotin the largerscale ofthings.Scala and manyotherhigh-level programming languages have been using sealed classestoo, aswell as sumtypesforquite sometime.
  • 6. Conflict With Encapsulation? Object-oriented modelling has always encouraged developersto keep the implementation of an abstracttype hidden. Butthen whyisthis newJava feature contradicting this rule?  When developers are modelling awell-understood and stable domain, encapsulation can be neglected because userswill notbe benefitting fromthe application ofencapsulation in this case. In theworstpossible scenario, itmayeven make itdifficultforclientstoworkwith avery simple domain. This does notmean thatencapsulation is a mistake. Itjustmeansthatata higherand complex level ofprogramming, developers are aware ofthe consequences. Sotheycan makethe callto go a bitoutoflineto getsomeworkdone. Sealed Classes And Records Sealed classesworkwellwith records (JEP384). Record is a relativelynewJava featurethatis a formofproducttype. Records are a newkind oftype declaration in Java similarto Enum. Itis a restricted formofclass. Records are implicitlyfinal, so a sealed hierarchywith records is slightlymore concise.To explain thisfurther,we can extend the previouslymentioned example using recordsto declarethe subtypes: 1. sealed interface Vehicle permits Car, Boat, Plane { 2. record Car (float speed, string mode) implements Vehicle {...} 3. record Boat (float speed, string mode) implements Vehicle {...} 4. record Plane (float speed, string mode) implements Vehicle {...} } This example shows howsumand record (producttypes)worktogether;we can saythata car, a plane ora boatis defined byits speed and its mode. In anotherapplication, itcan also be used forselecting which othertypes can bethe subclasses ofthe sealed class.  Forexample, simple arithmetic expressionswith records and sealed typeswould be likethe code mentioned below: 1. sealed interface Arithmetic {...} 2. record MakeConstant (int i) implements Arithmetic {...} 3. record Addition (Arithmetic a, Arithmetic b) implements Arithmetic {...} 4. record Multiplication (Arithmetic a, Arithmetic b) implements Arithmetic
  • 7. {...} 5. record Negative (Arithmetic e) implements Arithmetic {...} Herewe havetwo concretetypes: addition and multiplication which hold two subexpressions, and two concretetypes, MakeConstantand Negativewhich holds one subexpression. Italso declares a supertypeforarithmetic and capturesthe constraintthatthese are the only subtypes ofarithmetic. The combination ofsealed classes and records is also known as “algebraic datatypes”. Records allowusto express producttypes, and sealed classes allowusto express sumtypes. Records And Pattern Matching Both records and sealed types have an association with pattern matching. Records admiteasy decomposition intotheircomponents, and sealed types providethe compilerwith exhaustiveness information sothata switch thatcovers allthe subtypes need notprovide a defaultclause. A limited formof pattern matching has been previouslyintroduced in Java SE 14which will hopefullybe extended in thefuture.This initialversion ofJava feature allows Java developers to usetype patternsin “instanceof.” Forexample, let’stake a lookatthe code snippetbelow: 1. if (vehicle instanceof Car c) { 2. // compiler has itself cast vehicle to the car and bound it to c 3. System.out.printf("The speed of this car is %d%n", c.speed()); } Conclusion Although manyothertoolswere released with sealed classes, itremainsthe mostprominent Java feature ofthe release.We are still notcertain aboutthefinal representation ofsealed classes in Java. (Ithas been released as a previewin Java 15). Butsofarsealed classes are offering awide range ofuses and advantages.Theyproveto be useful as a domain modelling technique,when developers need to capture an exhaustive setofalternatives in the domain model. Sealed types become a natural complementto records, astogethertheyformcommon patterns. Both ofthemwould also be a natural fitfor pattern matching.  Itis obviousthat sealed classes serve as a quite useful improvementin Java.And,with the overwhelming
  • 8. JAVA FEATURE SEALED CLASSES SEALED CLASSES IN JAVA  0     Java Security Vulnerabilities: Case Commentary DECEMBER 15, 2020 What is TornadoVM? DECEMBER 10, 2020 Getting Comfortable With FPGAs DECEMBER 2, 2020 responsefromthe Java community,we can expectthata better, more refined version of sealed classes in Javawill soon be released. AUTHOR Shaharyar Lalani Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.  Name Email Website RELATED POSTS WRITE A COMMENT
  • 9. PDFmyURL.com - convert URLs, web pages or even full websites to PDF online. Easy API for developers! Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. POST COMMENT Enter your comment here.. SKILLSETS IN DEMAND Designers Developers Project Managers Quality Assurance Business Analysts QUICK LINKS Home Experts Clients FAQ's Privacy Policy CONNECT Contact Us     Copyright©2020.Allrights reservedbyXperti