Skip to main content

Kotlin Class Concept

Class is like a predefined code-templates, That is allow to define custom properties and functional methods. This properties and methods usability and accessibility by programmer logic under the define class rules. This mechanism is capable to controller different scenario and situations. And also possible to make a relation between properties and method of two classes. This relation are useful to access base class properties to derived class (Inherit class).

Actually class is binding the properties (fields) and methods into a single units, that are together perform relative task. Method and fileds is not directly accessible, that are used by class instance. This instance is know as class object.

Define a kotlin class

class is main concept of object oriented programming (oop). Kotlin programming is support this feature as well. Program can create custom class and also use existing inbuilt classes. In this post is focus, to define and use of user defined class. That syntax is very similar to java programming. There is syntax as follows.

class ClassName{
//data member (property)
//member function (operation)
}

In Kotlin Programming class keyword are used to define a class. The name of class define after this keyword. Note that the first characters of class name are should be capitalized because that is indicates name of class. Let see few basic declaration of class.

class Student{
  //class logic here
}
class Employee{
  //class logic here
}
class Manager{
  //class logic here
}

Body of class is not compulsory in kotlin programming we can define empty class.

class Execution

In this example Execution is an empty class. We can add empty class properties in latter. See this example.

class Execution

//Add function of Execution class
fun Execution.message(){
  println("Welcome to kotlin class")
}
fun main(args: Array<String>) {
   
   //execute class message function
   Execution().message()
}
Welcome to kotlin class

Execution().message() are execute class methods. Execution() are create a class instance. And that is execute message method of this class. You'll are learn more about objects in next section.

In this example first are defining a class Execution, after that added Execution.message() method to this class. Class name and using dot operator are added new method to existing class. But that is not a good standard way to define kotlin class. This is useful for add new features of existing class.

Best practice when create a custom user defined class then provides its data member and properties to inside class body. That is best way to organized class structures. For example.

class Execution{
    //class method
    fun message(){
      println("Welcome to kotlin class")
    }
}

fun main(args: Array<String>)  {
   
   //execute class message function
   Execution().message()
}
Welcome to kotlin class

Creating objects of class

Object are basically a variable which are hold the instance reference of class variables. val keyword are used to create an object which can be hold the any class instance reference. This type of object is cannot be-assigned other instance reference. In other sidevar type of objects are possible to assigned other reference.

class Calculation{
  //Define properties of class
    var data1 : Int = 0  //set default value
    var data2 : Int = 0  //set default value

    //Method which are set class instance variable value
    fun setData(data1:Int, data2:Int){
        this.data1 = data1
        this.data2 = data2
    }

    //Method which are display class instance variable value
    fun showData(){
        println("data1 : "+data1)
        println("data2 : "+data2)
    }
}


fun main(args: Array<String>) {
    //mutable objects
    var firstObj=Calculation()
    
    //immutable objects
    val secondObj=Calculation()
    

    firstObj.setData(10,20)
    
    secondObj.setData(2,7)
    
    firstObj.showData()
    
    secondObj.showData()
    
}
data1 : 10
data2 : 20
data1 : 2
data2 : 7

In this example Calculation() are creates an instance of class. Actually that is an constructor of class Calculation. In this case here not define any constructor. In this situation compiler are providing by default constructor. Constructor are create memory of instance variables of class and return the reference of instance. See this image.

kotlin-make objects of class

In this case class Calculation are create two objects. That object are store the reference of class instance. Note that class Calculation are defining of only two variable {data1,data2} We can define any other type of multiple variables but in this case are mentioning only two integer variables. Observe that each instance of class is contain copy of this variable.

When create each new instance of class using by class constructor they are allocated new memory of class instance variables. And variables which are store this instance reference that is called objects.

Objects of class are capable to use public methods of class. In Above image are initial state of object. We can set instance values by objects. In above program are changing the instance variable value by setData(Int,Int) method.

Change instance variable value

There is few important point, When in case not use class custom constructor to set initial value of variable. In this situation set default values to in its declaration. Otherwise compiler are produced an compilation error. See this example.

class Calculation{
  //Define properties of class
    var info : Int   //not set default value
  

    //Method which are set class instance variable value
    fun setData(info:Int){
        this.info = info
      
    }

    //Method which are display class instance variable value
    fun showData(){
        println("data1 : "+info)
        
    }
}
fun main(args: Array<String>) {
   
    var firstObj=Calculation()
    
}
source.kt:3:5: error: property must be initialized or be abstract
    var info : Int   //not set default value
    ^

Kotlin are strongly typed check programming language they are not provide usability of variable which is not assign initial values. So we can avoid this type of situation to use class constructor. Class constructor are very important part of class.

Kotlin Class Constructor

Constructor are used to assign initial value of instance variable fields. Kotlin are support two types of constructor Such as Primary constructor and secondary constructor.

Primary Constructor : This is header section construction that parameter will defined of the after the name of class within the parentheses.

class ClassName(var varName : DataType , val valName :DataType){
    
    //Class methods and propties
}

Primary constructor parameter list is a part of class instance variables means this parameter values are accessible in all method of class which are implement this constructor. And that values can be accessible by class objects.

class Student(val name : String,val standard : String){
    //Class method
    fun about(){
        println(" Name : "+name);
        println(" Standard : "+standard);
    }
}
fun main(args: Array<String>){ 
    //Make objects of class
    val first = Student("Angelina","5'th") //Executed primary constructor
    
    val second =  Student("Jolie","10'th") //Executed primary constructor
    
    first.about()
    
    //Accessing instance variable value by object
    println(" Hi,"+second.name);
   
} 
Instance variable
 Name : Angelina
 Standard : 5'th
 Hi,Jolie

Note that in this case primary constructor parameter data is of val type. So instance variables value are set when this constructor are execute after that this variable value are cannot modified. If you are need to modifed that value then you can choose var type.

Primary constructor parameter list is part of class instance variable. When defining others class instance variable within the class. In this situation you can init block to assign initial values to other class instance.

class Divides(val num1 : Int,val num2 : Int){
    var result : Int 
    init{
         //Set result variable value within the init block
        if(num2!=0){
            result = num1 / num2
        }
        else{
            result = 0
        }
        
    }
   
}
fun main(args: Array<String>){ 
    
    val obj = Divides(8,2)
    
    println("Result : "+obj.result) //4
   
} 

In this example there are total three instance variables of class {num1,num2,result}. Here two {num1,num2} values are set by primary constructor and {result} value are set by init block. Direct initialization are possible to class variable values.

class Sum(val num1 : Int,val num2 : Int){
    var result : Int =  num1 + num2
   
}
fun main(args: Array<String>){ 
    
    val obj = Sum(1,2)
    
    println("Sum : "+obj.result) //3
   
}

Secondary Constructor : This constructor are created by constructor keyword. The speciality of this constructor are we can create multiple variants.

class ClassName{  
    //First variant
    constructor(name : String){  
        //code here  
    }
    //Second variant  
    constructor(name : String, key : Int){  
        //code here
    }
    //Third variant
    constructor(name : String, key: Int, salary : Float){  
        //code here 
    }
} 

Constructors are automatically executes when objects are created. That execution is depends upon parameters of objects. Because there is possible to defining more than one constructors in same class. For example

class Info{  
     var data1 : Int
     var data2 : String 
     var data3 : Float 
    //First variant
    constructor(data1 : Int){  
        this.data1 = data1 
        //Set default value
        this.data2 = "First"
        this.data3 =1000.34f
        
    }
    //Second variant  
    constructor(data2 : String, data3 : Float){  
        //Set default value
        this.data1 = 2000 
       
        this.data2 = data2
        this.data3 = data3
    }
    //Third variant
    constructor(data1 : Int, data2 : String, data3 : Float){  
        this.data1 = data1 
        this.data2 = data2
        this.data3 = data3
    }
                
    fun dataInfo(){
        println("data1 : "+data1)
        println("data2 : "+data2)
        println("data3 : "+data3)
    }
}
fun main(args: Array<String>){ 
    
  val first = Info(1000)
  val second = Info("Second",20.19f) 
  val third = Info(3000,"Third",20.19f) 
    
  println("About First Object Data")
  first.dataInfo()
  println("About Second Object Data")
  second.dataInfo()
  println("About Third Object Data")
  third.dataInfo()
}
Multiple Construction Execution
About First Object Data
data1 : 1000
data2 : First
data3 : 1000.34
About Second Object Data
data1 : 2000
data2 : Second
data3 : 20.19
About Third Object Data
data1 : 3000
data2 : Third
data3 : 20.19

In this example there are three constructor are define in Info class. Each constructor of class are automatic execute based on parameter passing list. Suppose when, In case we are need execute one constructor inside another constructor. Then this() are used to do this task.

class Info{  
     var data1 : Int = 0
     var data2 : String  = ""
 
    //First variant
    constructor(data1 : Int){  
        this.data1 = data1 
        
    }
    //Second variant  
    //Execute first constructor
    constructor(data1 : Int, data2: String):this(data1){  
       
        this.data2 = data2
       
    }
                
    fun dataInfo(){
        println("data1 : "+data1)
        println("data2 : "+data2)
    }
}
fun main(args: Array<String>){ 
    

  val obj = Info(3000,"happy") 

  obj.dataInfo()
}
Use of multiple constructor
data1 : 3000
data2 : happy




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment