InterviewSolution
| 1. |
What do you understand about sealed classes in Kotlin? |
|
Answer» Kotlin introduces a crucial new form of class that isn't seen in Java. These are referred to as "sealed classes." Sealed classes, as the NAME implies, adhere to constrained or bounded class hierarchies. A sealed class is one that has a SET of subclasses. When it is known ahead of time that a type will conform to one of the subclass types, it is employed. Type safety (that is, the compiler will VALIDATE types during compilation and throw an exception if a wrong type has been assigned to a variable) is ensured through sealed classes, which limit the types that can be matched at compile time rather than runtime. The SYNTAX is as follows:- sealed class classNameAnother distinguishing aspect of sealed classes is that their constructors are by default private. Due to the fact that a sealed class is automatically abstract, it cannot be instantiated. For example, // KOTLINsealed class Sample { class A : Sample() { fun print() { println("This is the subclass A of sealed class Sample") } } class B : Sample() { fun print() { println("This is the subclass B of sealed class Sample") } }}fun main(){ val obj1 = Sample.B() obj1.print() val obj2 = Sample.A() obj2.print()}Output:- This is the subclass B of sealed class SampleThis is the subclass A of sealed class SampleExplanation:- In the above code, we have created a sealed class named “Sample” and we have created TWO sub classes within it named “A” and “B”. In the main function, we create an instance of both the sub classes and call their “print” method. |
|