Kotlin have ability to supports both object oriented programming (OOP) as well as functional programming. Object oriented programming that is oops is based on real time objects and classes. Kotlin also support function of OOP language such as encapsulation, inheritance and polymorphism.

Kotlin Class and Object

Kotlin class is similar to Java class, as we know that class is a blueprint for the objects which have same properties. In kotlin classes are declared using keyword class. Kotlin class contain a class header which help to specifies its type parameters, constructor etc. and class body is surrounded by curly braces.

Syntax of Kotlin class declaration

1. class className{   // class header  
2.       // property  
3.       // member function  
4. }  

Let’s see an example, class className which have an empty constructor. This constructor is generated by compiler automatically but if we need to define a constructor, we have to write a constructor keyword followed by class name like this:

1. class className constructor(){   // class header  
2.       // property  
3.       // member function  
4. } 

Example of Kotlin class

1. class account {  
2. var acc_no: Int = 0  
3. var name: String? = null  
4. var amount: Float = 0f  
5.   
6.     fun deposit() {  
7.         //deposite code  
8.     }  
9.   
10.     fun withdraw() {  
11.        // withdraw code  
12.     }  
13.   
14.     fun checkBalance() {  
15.         //balance check code  
16.      }  
17.   
18. } 

Kotlin Object

Like java kotlin support Object. An object can be real time entity or can be a logical entity which has state and behavior. It has some characteristics:

  • state: state represents value of an object which an object have.
  • behavior: state represent the functionality of an object which an object have.

We can use object to access the properties and member function of any class. Kotlin allows us to create multiple object of a class.

Create an object

In kotlin we can create object in two steps, the first is to create reference first and then create an object.

  1. var obj1 = className()  

Creating multiple object

  1. var obj1 = className()  
  2. var obj2 = className()  

In this obj1 and obj2 are reference of class and className() is an object.

Access class property and member function

In kotlin properties and member function of class are accessed by . operator with the help of object. For example:

  1. obj.deopsit()  
  2. obj.name = Veer 

Let’s see an example, which accessing the class property and member function with the help of . operator.

1. class Account {  
2.     var acc_no: Int = 0  
3.     var name: String =  ""  
4.     var amount: Float = 0.toFloat()  
5.     fun insert(ac: Int,n: String, am: Float ) {  
6.         acc_no=ac  
7.         name=n  
8.         amount=am  
9.         println("Account no: ${acc_no} holder :${name} amount :${amount}")  
10.     }  
11.   
12.     fun deposit() {  
13.         //deposite code  
14.     }  
15.   
16.     fun withdraw() {  
17.        // withdraw code  
18.     }  
19.   
20.     fun checkBalance() {  
21.         //balance check code  
22.      }  
23.   
24. }  
25. fun main(args: Array<String>){  
26.     Account()  
27.     var acc= Account()  
28.     acc.insert(12345,"Veer",4000f) //accessing member function  
29.     println("${acc.name}") //accessing class property  
30. }

Output:-

Account no: 12345 holder :Veer amount :4000.0
Veer

Kotlin Nested class and Inner class

Kotlin Nested class

Nested class is a type of class which is created inside another class. In Kotlin, nested class is treated as a static by default, so without creating object of this class we can access its data member and member function. But nested class unable to access the data member of outer class.

1. class outerClass{  
2.    //outer class code  
3.     class nestedClass{  
4.       //nested class code  
5.     }  
6. } 

Kotlin Nested Class Example

1. class outerClass{  
2.     private var name: String = "Ashu"  
3.     class nestedClass{  
4. var description: String = "code inside nested class"  
5.         private var id: Int = 101  
6.         fun foo(){  
7.           //  print("name is ${name}") // cannot access the outer class member  
8.          println("Id is ${id}")  
9.         }  
10.     }  
11. }  
12. fun main(args: Array<String>){  
13. // nested class must be initialize  
14. println(outerClass.nestedClass().description) // accessing property  
15. var obj = outerClass.nestedClass() // object creation  
16.     obj.foo() // access member function  
17. }

Output:-

code inside nested class
Id is 101

Kotlin Inner class

Inner class is a type of class which is created inside another class with the help of keyword inner. In other words, we can say that a nested class which is created with the keyword inner is called inner class.

here are some restriction of Inner class that is we  cannot be declared inside interfaces or non-inner nested classes.

1. class outerClass{  
2.    //outer class code  
3.     inner class innerClass{  
4.       //nested class code  
5.     }  
6. } 

The advantage of inner class  is that, it can access members of outer class even it is private. Inner class have a reference to an object of outer class.

Kotlin Inner Class Example

1. class outerClass{  
2.      private  var name: String = "Ashu"  
3.      inner class  innerClass{  
4. var description: String = "code inside inner class"  
5.         private var id: Int = 101  
6.        fun foo(){  
7. println("name is ${name}") // access the outer class member even private  
8. println("Id is ${id}")  
9.         }  
10.     }  
11. }  
12. fun main(args: Array<String>){  
13. println(outerClass().innerClass().description) // accessing property  
14. var obj = outerClass().innerClass() // object creation  
15.     obj.foo() // access member function  
16.   
17. }

Output:-

code inside inner class
name is Ashu
Id is 101

Kotlin Constructor

In Kotlin, constructor is a statement of code which is look like  method. We can declare constructor with the same name as the class followed by parenthesis ‘()’. Constructor is used for initialize the variables at the time of  when we create object  or object creation.

Types of Kotlin constructors

Kotlin have two types of constructors:

  1. Primary constructor
  2. Secondary constructor

We have  only one primary constructor in a Kotlin class but secondary constructor can be one or more.

Kotlin primary constructor

In kotlin we use primary constructor to initialize the class. It can be declare at class header. The code of Primary constructor have optional parameter under the parentheses

Let’s see an example which show how to define primary constructor. In this code, we declare a constructor myClass with two parameter name and id. 

class myClass(valname: String,varid: Int) {  
1.     // class body  
2. }  

When the object of myClasss is created, it will initialize name and id with “Veer” and “111” respectively.

1. class myClass(val name: String, var id: Int) {  
2. }  
3. fun main(args: Array<String>){  
4. val myclass = myClass ("Ashu", 101)  
5.   
6. println("Name = ${ myclass.name}")  
7. println("Id = ${ myclass.id}")  
8. }

Output:-

Name = Ashu
Id = 101

Primary constructor with initializer block

The primary constructor of koltin does not contain any code. In this initializer blocks are used to initialization of code. This block is comes with init keyword. At the time of instance initialization, the initialized blocks are executed in the same order as they places in class body.

Let’s have an example using initialize block:

1. class myClass(name: String, id: Int) {  
2. val e_name: String  
3. var e_id: Int  
4. init{  
5. e_name = name.capitalize()  
6. e_id = id  
7.   
8. println("Name = ${e_name}")  
9. println("Id = ${e_id}")  
10.     }  
11. }  
12. fun main(args: Array<String>){  
13. val myclass = myClass ("Ashu", 101)  
14.   
15. }

Output:-

Name = Ashu
Id = 101

Kotlin secondary constructor

In Kotlin, we can create secondary constructor one or more in class. The secondary constructor is created with the use of  “constructor” keyword.

Let’s see an example which define how to  declare secondary constructor. In the this code, we are going to declare two constructor of myClass with two parameter name and id.

1. class myClass{  
2.   
3.     constructor(id: Int){  
4.         //code   
5.     }  
6.     constructor(name: String, id: Int){  
7.         //code   
8.     }  
9. }  

Let’s have an example of secondary constructor which assign the value while object of class is created.

1. class myClass{  
2.   
3.     constructor(name: String, id: Int){  
4. println("Name = ${name}")  
5. println("Id = ${id}")  
6.     }  
7. }  
8. fun main(args: Array<String>){  
9. val myclass = myClass ("Ashu", 101)  
10.   
11. }

Output:-

Name = Ashu
Id = 101

In kotlin we can also use both primary as well as secondary constructor in a same class if we want .But if we are using primary as well secondary constructor in same class, secondary constructor has to authorize to primary constructor. We can do authorization to another constructor in same class is done using this() keyword.

For example:

1. class myClass(password: String){  
2.   
3.     constructor(name: String, id: Int, password: String): this(password){  
4. println("Name = ${name}")  
5. println("Id = ${id}")  
6. println("Password = ${password}")  
7.     }  
8. }  
9. fun main(args: Array<String>){  
10. val myclass = myClass ("Ashu", 101, "mypassword")  
11.   
12. }  

Output:-

Name = Ashu
Id = 101
Password = mypassword

Calling one secondary constructor from another secondary constructor of same class in Kotlin

In Kotlin, we can call one secondary constructor from another secondary constructor of same class with the help of this() keyword.

For example:

1. class myClass{  
2.   
3.     constructor(name: String, id: Int): this(name,id, "mypassword"){  
4. println("this executes next")  
5. println("Name = ${name}")  
6. println("Id = ${id}")  
7.     }  
8.   
9.     constructor(name: String, id: Int,pass: String){  
10. println("this executes first")  
11. println("Name = ${name}")  
12. println("Id = ${id}")  
13. println("Password = ${pass}")  
14.     }  
15. }  
16. fun main(args: Array<String>){  
17. val myclass = myClass ("Ashu", 101)  
18.   
19. } 

Output:-

this executes first
Name = Ashu
Id = 101
Password = mypassword
this executes next
Name = Ashu
Id = 101

Example of calling supper class secondary constructor from derived class secondary constructor In kotlin

Kotlin have ability in which one derived class secondary constructor can call the base class secondary constructor with the help of super keyword, this is the concept of inheritance.

1. open class Parent{  
2.   
3.     constructor(name: String, id: Int){  
4. println("this executes first")  
5. println("Name = ${name}")  
6. println("Id = ${id}")  
7.     }  
8.   
9.     constructor(name: String, id: Int,pass: String){  
10. println("this executes third")  
11. println("Name = ${name}")  
12. println("Id = ${id}")  
13. println("Password = ${pass}")  
14.     }  
15. }  
16. class Child: Parent{  
17.     constructor(name: String, id: Int): super(name,id){  
18. println("this executes second")  
19. println("Name = ${name}")  
20. println("Id = ${id}")  
21.     }  
22.   
23.    constructor(name: String, id: Int,pass: String):super(name,id,"password"){  
24. println("this executes forth")  
25. println("Name = ${name}")  
26. println("Id = ${id}")  
27. println("Password = ${pass}")  
28.     }  
29. }  
30. fun main(args: Array<String>){  
31. val obj1 = Child("Ashu", 101)  
32. val obj2 = Child("Ashu", 101,"mypassword")  
33. }

Output:-

this executes first
Name = Ashu
Id = 101
this executes second
Name = Ashu
Id = 101
this executes third
Name = Ashu
Id = 101
Password = password
this executes forth
Name = Ashu
Id = 101
Password = mypassword

You may also like...

0 Comments

No Comment.