
Java 15 Sealed classes/interface with example #Java15 #Sealed
Java 15 Sealed classes/interface with example #Java15 #Sealed
In this video, we learn about sealed classes and interfaces - a new preview feature in JDK 15.
You will understand the main goals of seal classes introduced in Java 15, and I will show you some code examples that help you understand the feature easily.
Content
0 -> Hello Everyone . In this vedio we will learn about
3.337 -> sealed classes which was released in Java 15.
5.076 -> First we will start with what is sealed classes ?
9.431 -> A sealed classes or interfaces are used to restrict
12.67 -> which other classes or interfaces may extend or implement them.
16.476 -> For example A graphics library and in it we have parent class called Shape
22.92 -> and it has subclasses
like Circle,Rectangle and Square .But one day
27.678 -> someone accidentally added a subclass called Music by
extending the class Shape.
32.566 -> The person who designed the graphics library did'nt want
35.708 -> Music to be a sub class of Shape.
38.136 -> So restricting the class hierarchy for this kind of situation java previously had only limited tools.
44.591 -> Either we have to make a class final, so it has zero subclasses,
48.489 -> or make a class or its constructor package-private,
52.647 -> it can only have subclasses in the same package.
56.806 -> Lets see an example in code.
59.854 ->
61.854 -> Here we have one interface called Shape and
68.103 -> 4 classes which are Circle,Music,Rectangle and Square.
72.576 -> Issue in this class design is that , music is not supposed to be sub class of Shape.
78.505 -> We can resolve this issue by restricting the sub classes or interface by using sealed classes or interface.
84.902 -> For this first we need to use sealed keyword
89.18 -> in Shape interface along with permits keyword which tells
following classes/interface are allowed to extend or implement Shape interface.
102.569 ->
108.338 ->
111.998 -> After making this change we can see compiler error in subclasses.
117.129 -> This is because subclasses must have a modifer which is either final , sealed or non sealed.
123.157 -> So that we can seal
the design in proper way.
126.153 -> If we make class as final then no other classes can extend this sub classes.
131.296 -> If we make class as sealed then we need to provide the sub classes which are allowed to extend.
136.669 -> if we make class as non sealed then unknown classes can extend the class.
141.754 -> for now we will use final modifier for all the sub classes
149.366 ->
163.475 -> But for music class we see compiler error because it is not permitted to implement Shape interface.
169.815 ->
173.848 -> So that all about sealed classes
176.993 -> I hope you understood this vedio, If you like this vedio
180.331 -> please click the like button and
183.124 -> If you want to see more vedios like this please click subscribe button
Source: https://www.youtube.com/watch?v=qfROX-6XiWU