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

PPT
Professional-core-java-training
PPT
Top 10 Interview Questions For Java
PDF
Professional-core-java-training
PPTX
Dev labs alliance top 20 basic java interview question for sdet
PDF
Vguruquickoverview_win_dec13
PPT
Classes and Objects
PPT
Java course-in-mumbai
PPT
8 most expected java interview questions
Professional-core-java-training
Top 10 Interview Questions For Java
Professional-core-java-training
Dev labs alliance top 20 basic java interview question for sdet
Vguruquickoverview_win_dec13
Classes and Objects
Java course-in-mumbai
8 most expected java interview questions

What's hot (8)

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

Similar to Java Feature Spotlight: Sealed Classes (20)

PDF
Sealed classes java
PDF
Advanced Programming _Abstract Classes vs Interfaces (Java)
PPTX
Getting the Most From Modern Java
DOCX
Core java notes with examples
PPTX
2CPP09 - Encapsulation
PPTX
Session 38 - Core Java (New Features) - Part 1
PDF
Java 17
PPTX
Objects and classes in OO Programming concepts
PDF
JAVA 3.1.pdfdhfksuhdfshkvbhdbsjfhbvjdzfhb
PDF
Exception handling and packages.pdf
PPT
Java inheritance
PPT
Chapter 5 declaring classes & oop
PDF
Java introduction
DOCX
Viva file
PPTX
The smartpath information systems java
PPTX
Abstract Class and Interface for Java Intoductory course.pptx
PPTX
Java Generics
PDF
java-06inheritance
PDF
Programming in Java Unit 1 lesson Notes for Java for Elearners
Sealed classes java
Advanced Programming _Abstract Classes vs Interfaces (Java)
Getting the Most From Modern Java
Core java notes with examples
2CPP09 - Encapsulation
Session 38 - Core Java (New Features) - Part 1
Java 17
Objects and classes in OO Programming concepts
JAVA 3.1.pdfdhfksuhdfshkvbhdbsjfhbvjdzfhb
Exception handling and packages.pdf
Java inheritance
Chapter 5 declaring classes & oop
Java introduction
Viva file
The smartpath information systems java
Abstract Class and Interface for Java Intoductory course.pptx
Java Generics
java-06inheritance
Programming in Java Unit 1 lesson Notes for Java for Elearners
Ad

More from Syed Hassan Raza (20)

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

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Electronic commerce courselecture one. Pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Empathic Computing: Creating Shared Understanding
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPT
Teaching material agriculture food technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation theory and applications.pdf
Review of recent advances in non-invasive hemoglobin estimation
Electronic commerce courselecture one. Pdf
Digital-Transformation-Roadmap-for-Companies.pptx
A Presentation on Artificial Intelligence
Diabetes mellitus diagnosis method based random forest with bat algorithm
Empathic Computing: Creating Shared Understanding
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Assigned Numbers - 2025 - Bluetooth® Document
Chapter 3 Spatial Domain Image Processing.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Building Integrated photovoltaic BIPV_UPV.pdf
A comparative analysis of optical character recognition models for extracting...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Big Data Technologies - Introduction.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation theory and applications.pdf

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