As the name suggests, a Sealed Class is a class that is sealed.
But Sealed from whom?
We will explain shortly. But before that let us list out a few properties of Sealed Class :
Now, let us understand Sealed Class with the below example:
So firstly, we will see the problem with a normal class. Then we will see how sealed class solves the problem.
Say, you have defined a class called Animal. And as we know, Animal is an abstract concept, i.e. Cat, Dog e.t.c are Animals. But an Animal doesn't exist on it's own.
So, you create an Abstract class called Animal. Then declare the classes Cat and Dog and make the Cat and Dog class a child of the Abstract class Animal.
And as we know, we need to define the classes within a Kotlin file. So, you create a Kotlin file with .kt extension, say, MyOwnFile.kt.
And define it as below.
abstract class Animal { } class Cat : Animal() { } class Dog : Animal() { }
Now, say there is a problematic developer in your team. All he does is, creates a class called House and makes it a child class of Animal(i.e. Your Abstract class).
And as usual, creates a new kotlin file, say, Kili.kt and places the House class in it.
class House : Animal() { }
Well! You know that House and Animal have no connection. But your problematic developer friend is doing it.
So, how can you stop him from doing that?
Quite simple! Just make the Animal class Sealed.
Make the Animal class Sealed using sealed keyword while declaring the class.
sealed class Animal { } class Cat : Animal() { } class Dog : Animal() { }
Now, when your problematic developer friend tries to create a child class of Animal, he gets an error.
class House : Animal() { }
So, quite tactfully you have solved the problem by making the Animal class sealed.
sealed class Animal { }
Just remember, all the subclasses of the sealed class must be defined within the same Kotlin file.