Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Class and Objects

In object-oriented programming (OOP), classes and objects are foundational concepts. A class is a blueprint or prototype for creating objects (a particular data structure), providing initial values for member properties, and implementing behavior in the form of member functions. In Kotlin, as in many other modern languages, working with classes and objects is straightforward.

1. Declaring a Class:

In Kotlin, you can declare a class using the class keyword:

class MyClass {
    // class body
}

2. Creating an Object (Instance):

Once a class is defined, you can create objects (instances) of that class using the constructor:

val obj = MyClass()

3. Class Constructors:

There are two types of constructors in Kotlin - primary and secondary:

Primary Constructor:

It is part of the class header and is declared after the class name:

class Person(val name: String, var age: Int) {
    // class body
}

In the example above, name and age are properties of the Person class, and you can create a new Person object by passing arguments to the primary constructor:

val person = Person("Alice", 30)

Secondary Constructor:

For additional ways to construct a class, you can use one or more secondary constructors. Each secondary constructor needs to delegate to the primary constructor using the this keyword:

class Person(val name: String, var age: Int) {
    constructor(name: String) : this(name, 0) {
        // additional code
    }
}

4. Member Functions:

A class can have member functions:

class Person(val name: String) {
    fun greet() {
        println("Hello, my name is $name.")
    }
}

val alice = Person("Alice")
alice.greet()  // Outputs: Hello, my name is Alice.

5. Member Properties:

A class can also have properties:

class Circle(val radius: Double) {
    val area: Double
        get() = Math.PI * radius * radius
}

val circle = Circle(5.0)
println(circle.area)  // Outputs the area of the circle

6. Inheritance:

By default, classes in Kotlin are final and cannot be subclassed. If you want a class to be inheritable, you must mark it with the open modifier:

open class Animal(val name: String) {
    fun eat() {
        println("$name is eating.")
    }
}

class Dog(name: String, val breed: String) : Animal(name) {
    fun bark() {
        println("$name is barking.")
    }
}

val rex = Dog("Rex", "Golden Retriever")
rex.eat()   // Outputs: Rex is eating.
rex.bark()  // Outputs: Rex is barking.

Conclusion:

This is a very basic introduction to classes and objects in Kotlin. There are more advanced features like data classes, sealed classes, abstract classes, companion objects, object declarations, etc., that you can explore as you get more familiar with Kotlin.

  1. Creating objects in Kotlin: Objects are instances of classes. You can create objects using the class keyword.

    class Person
    val person = Person()
    
  2. Properties and methods in Kotlin classes: Classes can have properties (variables) and methods (functions).

    class Person {
        var name: String = "John"
        fun sayHello() {
            println("Hello, $name!")
        }
    }
    
  3. Constructors in Kotlin classes: Constructors are special methods used for initializing objects.

    class Person(val name: String, val age: Int) {
        // ...
    }
    
  4. Visibility modifiers in Kotlin classes: Kotlin provides visibility modifiers like public, private, protected, and internal to control access to class members.

    class Example {
        private val secretValue = 42
    }
    
  5. Inheritance in Kotlin classes: Classes can inherit properties and methods from other classes using the : SuperClass() syntax.

    open class Animal(val name: String)
    
    class Dog(name: String) : Animal(name)
    
  6. Abstract classes in Kotlin: Abstract classes are partially implemented classes that cannot be instantiated on their own.

    abstract class Shape {
        abstract fun draw()
    }
    
  7. Interfaces in Kotlin: Interfaces define contracts that classes can implement. Multiple interfaces can be implemented by a single class.

    interface Printable {
        fun print()
    }
    
    class Document : Printable {
        override fun print() {
            println("Printing document...")
        }
    }
    
  8. Data classes in Kotlin: Data classes automatically generate common methods like toString(), equals(), and hashCode() based on the properties declared in the primary constructor.

    data class Person(val name: String, val age: Int)
    
  9. Companion objects in Kotlin: Companion objects are used to define static members or methods within a class.

    class MathUtils {
        companion object {
            fun add(a: Int, b: Int): Int {
                return a + b
            }
        }
    }
    
  10. Kotlin objects and singletons: The object keyword is used to define a singleton object. It is created only once, and its instance is accessible throughout the application.

    object Singleton {
        fun doSomething() {
            // ...
        }
    }
    
  11. Initialization blocks in Kotlin classes: Initialization blocks are used for additional setup during object creation.

    class Example {
        init {
            // Initialization code
        }
    }
    
  12. Kotlin class delegation: Kotlin supports class delegation, allowing one class to delegate certain operations to another class.

    interface Printer {
        fun print()
    }
    
    class BasicPrinter : Printer {
        override fun print() {
            println("Printing...")
        }
    }
    
    class AdvancedPrinter(printer: Printer) : Printer by printer