Understanding Classes In Kotlin

Introduction

This article will help you understand about different types of classes and their working in Kotlin.

Class

A class is a collection of data members and member methods. It behaves like a blueprint to create real-world entities, like objects.

General syntaxes to create a class without constructor and with constructor are shown below.

  1. class < className > (paramerers) {  
  2.     //datamembers  
  3.     //membermethods  
  4. }  
  1. class < className > {  
  2.     //datamembers  
  3.     //membermethods  
  4. }                                                               

Object

Object is a real world entity with the ability to access members of its class. General syntax to create an object is,

  1. Var <objectName>= <className>()  

Example

Simple program to illustrate a class and an object.

  1. class Book{  
  2.     var bookname:String="Handson kotlin"  
  3.     fun show() {  
  4.      println("Book name="+bookname)  
  5.         }  
  6.  }  
  7. fun main(args:Array<String>){  
  8.     var ob=Book();  
  9.     ob.show()  
  10. }  
Nested class

Class having a class within it is known as Nested class.

  1. class Outerclass{  
  2.     var a:Int=5  
  3.       class Nestedclass {  
  4.         var b:Int=10  
  5.         fun show() {  
  6.             // println("inside class value of a=" +a)    a is not accessible here  
  7.             println("inside class value of b=" +b)  
  8.         }  
  9.     }  
  10. }  
  11. fun main(args:Array<String>){  
  12.     var ob=Outerclass.Nestedclass()  
  13.     ob.show()  
  14.   
  15. }  
  16.   
  17. //Output: inside class valued of b=10  

Explanation

In the above example, I have created a nested class ‘Nestedclass’ which has a data member ‘b’ and a member method show(). Now, the object of the nested class can access the members of the nested class only.

Inner class

An inner class is a nested class which has ‘inner’ keyword and object of the inner class is able to access the inner class members as well as outer class members.

  1. class Outerclass{  
  2.     var a:Int=5  
  3.      inner class Innerclass {  
  4.   
  5.         fun show() {  
  6.   
  7.             println("inside inner class value of a=" +a)  
  8.         }  
  9.     }  
  10. }  
  11. fun main(args:Array<String>){  
  12.    var ob=Outerclass().Innerclass();  
  13.     ob.show()  
  14. }  
  15.   
  16. // output : inside class value of  a=5                                                                                                  
Anonymous class                 

It provides the facility to create an instance of Interface and Abstract classes indirectly. An instance created with the help of anonymous class is used only once.

  1. interface Animal{  
  2.     fun show()  
  3. }  
  4. fun main(args:Array<String>){  
  5.     var cow=object :Animal{  
  6.         override fun show() {  
  7.             println("Cow is a pet animal")  
  8.         }  
  9.   
  10.     }  
  11.     cow.show()  
  12. }  
  13.   
  14. //Output: Cow is a pet animal      

In this example, the compiler automatically creates a nested class to implement the Animal interface which will be instantiated and the reference will be passed to cow. Now, the cow object is able to call member method show().

This cow object will be used only once, then its space will be flushed.
Data Class

Data Classes or model classes are those classes which have data members and setter and getter methods. Since the basic concept of encapsulation states that the data member of a class should be private and member methods of the class may be public, when this class is initiated, the object will access the public member methods of the class and these public methods will access private data member of the class.

To create data classes like above, Kotlin uses a keyword ‘data’.

General Syntax

  1. data class < ClassName > (parameters) {  
  2.     //rest code  
  3. }  

Example

Write a program to illustrate the use of data classes in Kotlin.

  1. data class EmployeeInfo(var empid:Int,var empname:String){  
  2.     }  
  3. fun main(args:Array<String>){  
  4.     var object1=EmployeeInfo(101,"Mani Gautam")  
  5. println("empid="+object1.empid+",name="+object1.empname)  
  6. }  

Explanation

The above EmployeeInfo class is a data class which has two variables ‘empid’ and ‘empname’. Because of using data keyword, Kotlin automatically creates getter and setter methods along with copy(), equals(), and hashCode() etc. You can see all these codes in IntelliJ IDE by using ctrl+shift+A   ->show Kotlin bytecode -> decompile.                                           

  1. public final class EmployeeInfo {  
  2.     private int empid;  
  3.     @NotNull  
  4.     private String empname;  
  5.     public final int getEmpid() {  
  6.         return this.empid;  
  7.     }  
  8.     public final void setEmpid(int var1) {  
  9.         this.empid = var1;  
  10.     }  
  11.     @NotNull  
  12.     public final String getEmpname() {  
  13.         return this.empname;  
  14.     }  
  15.     public final void setEmpname(@NotNull String var1) {  
  16.         Intrinsics.checkParameterIsNotNull(var1, "<set-?>");  
  17.         this.empname = var1;  
  18.     }  
  19.     public EmployeeInfo(int empid, @NotNull String empname) {  
  20.         Intrinsics.checkParameterIsNotNull(empname, "empname");  
  21.         super();  
  22.         this.empid = empid;  
  23.         this.empname = empname;  
  24.     }  
  25.     public final int component1() {  
  26.         return this.empid;  
  27.     }  
  28.     @NotNull  
  29.     public final String component2() {  
  30.         return this.empname;  
  31.     }  
  32.     @NotNull  
  33.     public final EmployeeInfo copy(int empid, @NotNull String empname) {….  
  34.         return new EmployeeInfo(empid, empname);  
  35.     }  
  36.     public String toString() {  
  37.         return "EmployeeInfo(empid=" + this.empid + ", empname=" + this.empname + ")";  
  38.     }  
  39.     public int hashCode() {  
  40.         return this.empid * 31 + (this.empname != null ? this.empname.hashCode() : 0);  
  41.     }  
  42.     public boolean equals(Object var1) { ...............  
  43.     }  
  44. }  
Sealed class

Sealed class is a class which can not be initiated directly. It has private constructors by default and abstract members .These are used to represent the restricted class hierarchy.

General syntax -

  1. sealed class < ClassName > {  
  2.     //rest code  
  3. }  

Example

Write a program to illustrate a sealed class.

  1. sealed class Student(id: Int) {  
  2.     fun graduate() {  
  3.         println("student of")  
  4.     }  
  5.     class Btech: Student(5) {  
  6.         fun show_btech() {  
  7.             println("BTech")  
  8.         }  
  9.     }  
  10.     class Bca: Student(5) {  
  11.         fun show_bca() {  
  12.             println("BCA")  
  13.         }  
  14.     }  
  15. }  
  16. fun main(args: Array < String > ) {  
  17.     var obj = Student.Btech()  
  18.     obj.graduate()  
  19.     obj.show_btech()  
  20.     Student.Btech().show_btech()  
  21.     Student.Bca().show_bca()  
  22. }  
  23. //output:  
  24. Btech  
  25. Btech  
  26. Bca                                                                                                         

Explanation

I have created this example in a single file ‘Example_sealed_class.kt’. So, I am able to inherit this class in two subclasses (‘Btech and Bca’) but this class will not be inherited in another class from another file.

Enum Classes

It is a special type which allows a variable to hold the value from predefined constants. It can not initiate.

  1. enum class < ClassName > {  
  2.     member1,  
  3.     member2,  
  4.     member3  
  5. }  

Example

  1. enum class week {  
  2.     monday, tuesday, wednessday, thursday, friday, saturday, sunday  
  3. }  
  4. fun main(args: Array < String > ) {  
  5.     //println(week.monday)  
  6.     //or  
  7.     /*week.values().forEach { 
  8.         println(it) 
  9.     }*/  
  10.     for (day in week.values()) {  
  11.         print(day)  
  12.     }  
  13. }  
  14. //output: monday tuesday  wednesday thursday friday saturday sunday  

Explanation

In this example, week class has 7 days as constant values. We can access these values by using class name.value’ or when we use ‘week.values() ‘ it will return an array of week class data, which can be accessed by using Foreach loop.

Genric class

As we know, to declare a variable, the data type is required which creates a restriction to have value of the specific type, i.e., an ‘Int’ type  variable can hold integer value a String type variable can hold only String value. To resolve it, we can create ‘Genric’ classes to create variable of general type.

Example

  1. class GenricExample < T > (param: T) {  
  2.     init {  
  3.         println("curent value=$param")  
  4.     }  
  5. }  
  6. fun main(args: Array < String > ) {  
  7.     var obj = GenricExample < String > ("Hello Genric")  
  8. }  
  9. //output: curent value=Hello Genric                                                                                                                                                                                                            

In this example, I am creating  a class ‘GenricExample’ as Genric type where programmer can specify type of parameter while initiating class. This same class can be used to create variable of different – different type.  

It provides two keywords,

  1. out- keyword is use to assign any Generic type to its supper type
  2. in – keyword is use to assign supper type to Generic type
  1. class GenricExample < out T > (param: T) {  
  2.     init {  
  3.         println("curent value=$param")  
  4.     }  
  5. }  
  6. fun main(args: Array < String > ) {  
  7.     var obj = GenricExample < Int > (10)  
  8.     println(obj)  
  9. }  
  10. //output: curent value=Hello  

You can use ‘in’ keyword also in similar example

Abstract class

Abstract classes have  abstract methods (a method which has abstract modifier but does not have definition) and concurrent methods (the method which does not have abstract modifier but holds definition).The abstract methods of Abstract class will be overridden in its subclass. But we can’t override concurrent methods of abstract class. Abstract class can’t be initiated.

Syntax

  1. abstract class < ClassName > {  
  2.     abstract fun method1()  
  3.     abstract fun method2 {}  
  4. }  

Example

  1. abstract class Animal {  
  2.     abstract fun show()  
  3.     fun attributes() {  
  4.         println("cow has four lags")  
  5.     }  
  6. }  
  7. class Cow: Animal() {  
  8.     override fun show() {  
  9.         println("Cow is a pet Animal")  
  10.     }  
  11. }  
  12. fun main(args: Array < String > ) {  
  13.     var cow = Cow()  
  14.     cow.show()  
  15.     cow.attributes()  
  16. }  

Explanation

In the above example, there is an abstract class named Animal which has one abstract function ‘show()’ and one concurrent function ‘attributes()’.Abstract function is being overridden in Cow subclass and subclass ‘Cow ’ is being instantiated in main function.

We can’t create object of Abstract class directly.
Conclusion

Kotlin also supports maximum framework classes of Java so you can implement your Java concepts in Kotlin too. Hope this article is helpful to understand different types of classes in Kotlin.

See my previous articles if you did not see them yet and follow me to have notifications for my upcoming articles.


Similar Articles