Week 2

Lecture dates: April 3rd and 5th

It's time to learn more about Kotlin. This week we will begin by touching on inheritance as well as classes, objects, constructors, and initializers.

It is important that you master these topics in order to maximize Kotlin's capabilities and effectiveness when developing your application.

All details on these topics are readily available to read in the course's slide (in Canvas).

Inheritance

Inheritance is very important in Object Oriented Programming (OOP) no matter which programming you are using that supports it. Using inheritance, we can re-use classes. We do so by "inheriting" properties and methods from another class.

A parent/base class may contain properties and methods that a sub/child class can inherit from. In Kotlin, a base class has a base class called Any . To allow a class to be inheritable by others, the methods must be marked with an open modifier.

// This is a parent class
open class Employee(val name: String, val job: String) {
    // Declare methods and properties here
}

class HR(val name: String, val job: String, val client: String) : Employee(name, job) {
    // Declare methods and properties here
}

You can find further details about inheritance by reading this useful article.

Classes, Objects, Constructors, Initializers

Unlike Java, Kotlin doesn't require you to use the new keyword each time you want to instantiate a class.

class Person {
    var firstName: String = "Naruth"
    var lastName: String = "Kongurai"
}

Usually you'll want to have a constructor that accepts a list of comma-separated parameters:

class Person constructor(_firstName: String, _lastName: String) {
    init {
        println("Hello, $firstName $lastName")
    }
}

Notice the _ (underscore) before firstName and lastName. Using init, we initialized the properties of a class based on the parameters we passed to the constructor. Doing so allows you to create an instance of the above class by writing:

val p1 = Person("Naruth", "Kongurai")
val p2 = Person("Ted", "Neward")

But what if we want to provide default values for our properties? You can easily do so by adding an = ... directly after declaring the property for each parameter. Here's an example:

class Person constructor(var firstName: String = "Mr.", var lastName: String = "Unknown") {

There's a whole lot more to these topics than what's mentioned above, such as secondary constructors, creating getters and setters, and visibility modifiers (public, private, protected, and internal). You can learn more about them by reading this article.

Last updated