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

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

What's hot (8)

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

Similar to Java Feature Spotlight: Sealed Classes

Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
Raghavendra V Gayakwad
 
1
11
gopal hp
gopal hpgopal hp
Core java questions
Core java questionsCore java questions
Core java questions
Pradheep Ayyanar
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
homeworkping7
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Ankit Prajapati
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Ankit Prajapati
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Gradeup
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
mrxyz19
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
Questpond
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
satish reddy
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
satish reddy
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
Techglyphs
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
yearninginjava
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
Gaurav Maheshwari
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
Rich Helton
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
Kuntal Bhowmick
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdet
DevLabs Alliance
 
Project 2 Instructions.htmlCompetencyIn this project, you .docx
Project 2 Instructions.htmlCompetencyIn this project, you .docxProject 2 Instructions.htmlCompetencyIn this project, you .docx
Project 2 Instructions.htmlCompetencyIn this project, you .docx
denneymargareta
 

Similar to Java Feature Spotlight: Sealed Classes (20)

Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
1
11
1
 
gopal hp
gopal hpgopal hp
gopal hp
 
Core java questions
Core java questionsCore java questions
Core java questions
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLT
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLT
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdet
 
Project 2 Instructions.htmlCompetencyIn this project, you .docx
Project 2 Instructions.htmlCompetencyIn this project, you .docxProject 2 Instructions.htmlCompetencyIn this project, you .docx
Project 2 Instructions.htmlCompetencyIn this project, you .docx
 

More from Syed Hassan Raza

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

More from Syed Hassan Raza (20)

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

Recently uploaded

HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 

Recently uploaded (20)

HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Artificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic WarfareArtificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic Warfare
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 

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