Start learning free

LESSON 176 OF 348 · FUNCTIONS & CLASSES

Classes in Kotlin: Properties, Constructors and Methods

Lesson Read the full explanation

Java is an object oriented programming language. Almost everything in Java is an object, with its attributes and methods.

Class creates a user-defined data structure, which holds its own data members (attributes) and member functions (methods), which can be accessed and used by creating an instance of that class.

Classes are like a blueprint for objects outlining possible behaviors and states that every object of a certain type could have.

Classes are defined via the keyword class, like this:

// Define an empty class Employee
class Employee {

}

Objects/Instances

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual employee, like a person named "Andrew" who is 30 years old.

You can have many employees to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.

After a class is defined, we can create objects of the class using the new keyword like this:

// Define an empty class Employee
class Employee {

}

// inside main function:
val employee = Employee()

Attributes/Properties

A class attribute is a Java variable that belongs to a class and is shared between all the objects of this class. Let's add some attributes to our Employee class:

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

// inside main function:
val emp1 = Employee()
	
emp1.name = "Andrew"
println(emp1.name) // prints "Andrew"
	
val emp2 = Employee()
	
emp2.age = 40
println(emp2.age) // prints 40

We added two properties: the String name and the int age. Then, we created two different Employee objects emp1 and emp2.

The attributes of objects can be accessed and modified using the dot operator (.), like we did above with emp1.name and emp2.age.

The keyword public used inside the class is called an access specifier. name and age are public attributes, whch means they can be accessed from anywhere in the code, not just inside the class code.

Constructors

In real life, we want to set the attributes specific to each object when creating it. For example, an employee named Andrew of 30 years old and another one named Mary of 25 years old. Here the constructor comes to rescue.

A constructor is a special type of method (function) which is used to initialize the instance members of the class.

In Java the constructor method has the same name as that of its class and is always called when an object is created.

Let's add a constructor to our Employee class:

class Employee {
	var name: String = ""
	var age: Int = 0
	
	// constructor:
	constructor(name: String, age: Int) {
		this.name = name
		this.age = age
	}
}

// inside main function:
val emp1 = Employee("Andrew", 30)
	
println(emp1.name)
	
val emp2 = Employee("Mary", 25)

println(emp2.age)

// prints "Andrew" and 25 on different lines

The "this"

Every object in Java has access to its own address through an important refference called this.

The this refference is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to access and manipulate the attributes of that object, like we did above with this.name = name.

Member functions

Member functions are functions that belong to the class:

class Employee {
	var name: String = ""
	var age: Int = 0
	
	// constructor:
	constructor(name: String, age: Int) {
		this.name = name
		this.age = age
	}
	
	//member functions:
	fun printName() {
		println(name) // it is not mandatory to use "this" to access an attribute
	}
		
	fun printEmployee() {
		printName()
		println(age)
	}
}

// inside main function:
val emp1 = Employee("Andrew", 30)

emp1.printEmployee() // prints "Andrew", 30
	
val emp2 = Employee("Mary", 25)

emp2.printEmployee() // prints "Mary", 25

As you can see, we access functions just like we access attributes: using the dot syntax (.).

The function call uses the attributes of the object it was called on. That's why the first printEmployee() prints 'Andrew' and 30 and the second prints 'Mary' and 25.


Assignment
Follow the Coding Tutorial and let's write some classes.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS & CLASSES

    Classes in Kotlin, explained

    What a class is

    A class is a blueprint. It describes what data an object holds and what the object can do. An object (also called an instance) is one concrete thing built from that blueprint, with real values. Employee can be a class, while an employee named Andrew who is 30 years old is an object. One class can produce many objects, each with its own values.

    A class is declared with the class keyword:

    class Employee {
    }
    

    Creating objects

    Kotlin creates an object by calling the class name like a function. There is no new keyword:

    val employee = Employee()
    

    The variable is a val, so it always refers to the same object. That doesn't stop the object's own var properties from changing.

    Properties

    Variables that belong to an object are called properties. Each object gets its own copy. Declare them inside the class body with var (can be reassigned) or val (cannot), and give them an initial value:

    class Employee {
        var name: String = ""
        var age: Int = 0
    }
    
    fun main() {
        val emp1 = Employee()
        emp1.name = "Andrew"
        println(emp1.name) // Andrew
    
        val emp2 = Employee()
        emp2.age = 40
        println(emp2.age)  // 40
    }
    

    The dot operator reads or writes a property: emp1.name. Changing emp1 doesn't affect emp2, since each has separate storage. Properties and members are public by default in Kotlin, so no keyword is needed for code outside the class to use them. Marking a member private hides it: reading a private count from outside the class is a compile error.

    Constructors

    Usually you want to set the values while creating the object. A constructor does that. Kotlin's most common form is the primary constructor, written in the class header:

    class Person(val name: String, var age: Int) {
        fun describe() {
            println("$name is $age")
        }
    }
    
    fun main() {
        val p = Person("Mary", 25)
        p.describe() // Mary is 25
    }
    

    Writing val or var before a parameter in that header declares a property and sets it from the argument in one step. Without it, the parameter exists only for initialization and can't be used inside methods. This is the form the lesson's exercise uses.

    A class can also declare a secondary constructor with the constructor keyword, which is useful when you want several ways to create objects. In that form the properties are declared in the body and assigned with this:

    class Employee {
        var name: String = ""
        var age: Int = 0
    
        constructor(name: String, age: Int) {
            this.name = name
            this.age = age
        }
    }
    

    Inside a class, this refers to the object being worked on. Here this.name is the property, and plain name is the parameter that shadows it. Without a name clash, this. is optional. The primary constructor form is shorter and is the one to prefer.

    Methods

    Functions declared inside a class are called methods (or member functions). They are called with the dot syntax on an object and can use that object's properties directly:

    class Person(val name: String, var age: Int) {
        fun birthday() {
            age += 1
        }
    
        fun describe() {
            println("$name is $age")
        }
    }
    
    fun main() {
        val p = Person("Mary", 25)
        p.birthday()
        p.describe() // Mary is 26
    }
    

    A method without a declared return type returns Unit, Kotlin's counterpart of void.

    The exercise, step by step

    The lesson asks for a class Job with a title and a method that announces the job, then uses it inside mainFunction.

    1. Declare class Job above Solution, with var title: String in the primary constructor. Declaring and storing the title takes one line.
    2. Add a method hireMe inside Job, with fun and no parameters.
    3. Print the message in the method: "You're hired as a " followed by title, joined with +. The property is available directly, without this.
    4. Create the object in mainFunction: val job = Job("Software Engineer").
    5. Call the method with job.hireMe(). Creating the object prints nothing by itself; the message appears when the method runs.
    class Job(var title: String) {
        fun hireMe() {
            println("You're hired as a " + title)
        }
    }
    
    class Solution {
        fun mainFunction() {
            val job = Job("Software Engineer")
            job.hireMe()
        }
    }
    

    When mainFunction runs, it prints You're hired as a Software Engineer. A string template, "You're hired as a $title", would give the same text, and it is the more common style.

    Common mistakes

    • Leaving out val or var in the constructor header. class Job(title: String) compiles, but title is then only a constructor parameter. Using it inside hireMe fails with an unresolved reference.
    • Using new. Kotlin has no such keyword. Write Job("...").
    • Reassigning a val property. If title were declared with val, then job.title = "Manager" would not compile. Use var for properties that change.
    • Forgetting the parentheses on a call. job.hireMe without () doesn't run the method.
    • Comparing objects with ==. For an ordinary class, == is true only for the same object, so two Person("a", 1) objects are not equal. Kotlin's data class changes that.

    Key takeaways

    • A class defines the properties and methods; objects are created by calling the class name.
    • Put val or var before a primary-constructor parameter to make it a property.
    • Members are public by default, and private hides them.
    • Methods are called with the dot, and they use the object's own properties.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free