Class In Kotlin

Class in Kotlin

Think of Class as a blueprint of a house and object as a house built from that same blueprint. Just like a blueprint which contains all the design layout with which you can build a house, a Class contains all the elements to build an object. This concept of class and an object is called object oriented programming. In a class, we define all the attributes and functions and using the class we create objects. The attribute becomes the state of the object and function becomes the behavior of the object. Therefore, the house as an object will have :
  • State as dimensions, materials, etc
  • behavior as providing shelter, protection from rain, etc
In Object Oriented programming (OOP), what we do is create multiple classes to divide the program efficiently so that we can reuse same class in different areas of code as objects. We can create as many objects as we want from the same class with different states.
Hierarchical structure of OOP also gives us the ability to inherit features from parent class to child class.
A typical Kotlin class can contain the following elements:
  1. functions
  2. properties or attributes
  3. Constructors
  4. Object declaration
  5. Inner classes
We are going to go in-depth in each of the listed above.

Basic Syntax

Basic example of Class and object

class NewClass                    //creation of a new class
    fun add(num1: Int,num2: Int) :Int    //creation of function to add 2 numbers
        return num1 + num2        //send back the added result

fun main(args: Array)              //main function from which code will run
    val NewObject=NewClass()     //creating object from NewClass
    val sum=NewObject.add(1,2)   //using the object to call add function
    print(sum)                     //printing the result