Creating Classes in Kotlin

In this article, I will explain how to create Classes in Kotlin. Like other programming languages, the class keyword is used to define a class in Kotlin. Moreover, classes in Kotlin can have properties, methods, and constructors as its members. The following code shows the syntax of creating classes in Kotlin.

Unlike Java, it is not mandatory to have classes in a Kotlin program. Hence, we can define the main() method outside a class in Kotlin. The following code demonstrates how to create classes in Kotlin.

Primary and Secondary Constructors

As can be seen, the program contains two classes. Also, the program demonstrates the usage of the primary constructor and the init block. While we can use the primary constructor in the class header, a class can also have one or more secondary constructors. Secondly, the init() block initializes the properties of a class. Moreover, it is not necessary to pass the same number of parameters in the primary constructor as the number of fields in the class. Evidently, the class named MyClass has only one parameter that is used to initialize all the fields of the corresponding class.

Example of Creating Classes in Kotlin

class ClassDemo1(val i: Number, val j: Number) {
    var num1: Number
    var num2: Number

class MyClass(val x: Number)
    var p: Number
    var q: Number
    var r: Number

fun main(args: Array<String>)
    val ob=ClassDemo1(10, 20)
    println("First: ${ob.num1}, Second: ${ob.num2}")
    val i=30;
    val ob1=ClassDemo1(i, i*4)
    println("First: ${ob1.num1}, Second: ${ob1.num2}")

    val ob2=MyClass(3.5)
    println("${ob2.p}, ${ob2.q}, ${ob2.r}")

So, when you run this program, statements contained in the main() method will execute in a sequential manner. Further, a new keyword is not required to create an instance of a class in Kotlin. As shown above, we create the first object of the class ClassDemo1 by providing the constant values. However, it is also possible to use expressions while passing the parameters. This is evident from the statement that creates the second object.

After that, we create an object of the class named MyClass, by providing only one value to the constructor that will initialize all of its fields.


Example of Creating Classes in Kotlin
Example of Creating Classes in Kotlin

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *