Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




KOTLIN - SEALED CLASS


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 :

  1. A sealed class is abstract by default and cannot be instantiated. i.e. We cannot create an object of a Sealed Class.

  2. In a Sealed Class, the constructors are private by default.

  3. To define a Sealed Class, mention sealed keyword before class keyword.

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.


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.


MyOwnFile.kt


abstract class Animal {

}

class Cat : Animal() {

}

class Dog : Animal() {

}

Note : For simplicity we have kept the bodies of Cat, Dog and Animal classes empty.


The problematic developer


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.


Kili.kt


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.


Problem solved with Sealed Class


Make the Animal class Sealed using sealed keyword while declaring the class.


MyOwnFile.kt


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.


Kili.kt


Example :



class House : Animal() {

} 


Output :



  Cannot access '<init>': it is private in '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.