How do I create a class and an object in Kotlin?

In Kotlin, you create a class with the class keyword, and you create an object instance by calling the class constructor.

class Person {
    var name: String = "Unknown"
    var age: Int = 0
}

fun main() {
    val person = Person()

    person.name = "Alice"
    person.age = 25

    println("${person.name} is ${person.age} years old")
}

Output:

Alice is 25 years old

Class with a constructor

A more common Kotlin style is to define properties directly in the constructor:

class Person(
    val name: String,
    var age: Int
)

fun main() {
    val person = Person("Alice", 25)

    println("${person.name} is ${person.age} years old")
}

Here:

  • class Person(...) defines a class.
  • val name is a read-only property.
  • var age is a mutable property.
  • Person("Alice", 25) creates an object of the class.

Kotlin object keyword

Kotlin also has the object keyword, which creates a singleton object:

object AppConfig {
    val appName = "My Kotlin App"
    val version = "1.0"
}

fun main() {
    println(AppConfig.appName)
    println(AppConfig.version)
}

Unlike a class, you do not create instances of an object. There is only one instance, and you access it directly by name.

How do I clone an object?

To enable our object to be cloned we need to override Object class clone method. We can also add a java.lang.Cloneable interface to our class, this interface is an empty interface. When we call the clone() method we need the add a try-catch block to catch the CloneNotSupportedException. This exception will be thrown if we tried to clone an object that doesn’t suppose to be cloned.

Calling the clone() method does a stateful, shallow copy down inside the Java Virtual Machine (JVM). It creates a new object and copies all the fields from the old object into the newly created object.

package org.kodejava.basic;

public class CloneDemo implements Cloneable {
    private int number;
    private transient int data;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) {
        CloneDemo clone = new CloneDemo();
        clone.number = 5;
        clone.data = 1000;

        try {
            // Create a clone of CloneDemo object. When we change the value of
            // number and data field in the cloned object it won't affect the
            // original object.
            CloneDemo objectClone = (CloneDemo) clone.clone();
            objectClone.number = 10;
            objectClone.data = 5000;

            System.out.println("cloned object = " + objectClone);
            System.out.println("origin object = " + clone);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    public String toString() {
        return "[number = " + number + "; data = " + data + "]";
    }
}

How do I get super class of an object?

To get the super class of an object we can call the object’s getClass() method. After getting the class type of the object we call the getSuperclass() method to get the superclass. Let’s see the code snippet below.

package org.kodejava.lang;

public class ObtainingSuperClass {
    public static void main(String[] args) {
        // Create an instance of String class
        Object object1 = new String("Hello");

        // Get String class super class
        Class<?> clazz1 = object1.getClass().getSuperclass();
        System.out.println("Super Class = " + clazz1);

        // Create an instance of StringIndexOutOfBoundsException class
        Object object2 = new StringIndexOutOfBoundsException("Error message");

        // Get StringIndexOutOfBoundsException class super class
        Class<?> clazz2 = object2.getClass().getSuperclass();
        System.out.println("Super Class = " + clazz2);
    }
}

The program above prints the following string:

Super Class = class java.lang.Object
Super Class = class java.lang.IndexOutOfBoundsException