Skip to content

Kotlin Fundamentals: Classes

Devrath edited this page Jan 26, 2024 · 8 revisions

Ksp2-Preview-Kotlin-K2-Banner

1. Classes are public by default

2. Classes are Final by default

If you want to Inherit a class, You need to mark it as open indicating that it can be inherited explicitly

3. Will have a primary constructor

This primary constructor is used to create an instance

    fun primaryConstructorDemo() {
        val science = Science()
        val history = History()
        // val maths = Maths() // Cannot access '<init>': it is private in 'Maths'
    }
    
    // Class with default constructor(way 1)
    class Science()
    // Class with default constructor(way 2)
    class History constructor()
    // Class with private constructor
    class Maths private constructor()
    // Class with protected constructor constructor
    class Computers protected constructor()

4. Might have multiple constructors

When using a secondary or ternary constructor etc we should call the primary constructor if the primary constructor has variables.

    fun secondaryConstructorDemo(){
        val mechanical = Mechanical(name = "CustomName", noOfPages = 10)
    }

    class Mechanical(val name:String){
        constructor(name: String, noOfPages:Int) : this(name)
    }

5. No need to use the new keyword to create an object of the class like we do in Java

6. Classes can be abstract like in other languages

7. They may have properties and methods

8. Properties of the class are private by default

We can mark it as val or var thus it becomes public

    class Person(name: String)
    class Student(val name: String)

    fun test() {
        val person = Person("Donald")
        person.name // Unresolved reference: name

        val student = Student("Einstein")
        student.name // We can access the name variable
    }

9. Using the init{} block in class

  • We cannot execute the code in the constructor like how we did in Java
  • If we want some code to be executed when the object is created we can use init block.
  • In the init block, We have access to the values passed to the constructor variables output
Before City Class construction
City is created with Name:-> New York
After City Class construction
City construction is in progress

code

    fun initBlockSignificanceDemo() {
        println("Before City Class construction")
        val demo = City("New York")
        println("After City Class construction")
        demo.demo()
    }

    class City(val name: String){
        init {
            println("City is created with Name:-> $name")
        }

        fun demo(){
            println("City construction is in progress")
        }
    }
Clone this wiki locally