Kotlin- Create Class Example

A class is a blueprint/template for creating objects of similar type. The objects contain state in the form of member variables (properties) and behavior in the form of member functions (methods). You can create a Class in Kotlin using the class keyword.

Kotlin- Create Class Example

In this below, we have created a User class with properties firstName and lastName.

package net.javaguides.kotlin.examples

class User {
    // Properties or Member Variables
    var firstName: String;
    var lastName: String;

    // Secondary Constructor
    constructor(firstName: String, lastName: String) {
        this.firstName = firstName
        this.lastName = lastName
    }
}

fun main(args: Array < String > ) {
    val person = User("Tony", "Stark")
    println(person.firstName) // Tony
    println(person.lastName) // Stark
}
Output:
Tony
Stark




Comments