Kotlin Tutorial
Kotlin Classes
Kotlin Classes & Objects:
- Class: A class is used as a template for creating the objects.
- Object: An object is the instance of the class
Classes in Kotlin are declared with the keyword “class”:
Example:
// keyword class - with class name and open body + some properties.
class Human {
var name = "John"
var age = 50
var height = "7 feet"
}
Note: class names should start from capital letters e.g Car, Person, Human etc.
Create the object of the class.
To create an object of the class use the name of the class.
Example:
// create object - using class name
val h1 = Human();
Now access the properties of the class by using ( . )
Example:
// create object - using class name
val h1 = Human();
// access properties by ( . ) - and store it in a variable
val name = h1.name
val age = h1.age
val height = h1.height
// print it then :)
println(name)
println(age)
println(height)
The code above will outputs:
John
50
7 feet
Or you can also do:
println("My name is $name; and I'm $age years old, my height is $height.")
The code above will outputs:
My name is John; and I'm 50 years old, my height is 7 feet.
Create multiple objects of the class.
To create multiple objects of a single class do:
Example:
// object - 1
val h1 = Human()
// object - 2
val h2 = Human()
We got two humans (objects of a Human class) ; programming is easy right? 😄
Let’s do something more interesting:
We have a class called Human; first Let’s modify it.
class Human {
var name = ""
var age = 0
var height = ""
}
Well, why did we do this? Lemme show you why:
Create two objects same as above in the example:
// object - 1
val h1 = Human()
// object - 2
val h2 = Human()
Done?
Good, now access their properties and assign them new fresh values e.g name, age and height.
Example:
// object - 1
val h1 = Human()
h1.name = "John"
h1.age = 50
h1.height = "4 feet"
// object - 2
val h2 = Human()
h2.name = "Steve"
h2.age = 23
h2.height = "6 feet 2inch"
We got 2 humans (objects) with different bio data (properties). Let’s print them now.
// Human 1
println("My name is ${h1.name}; and I'm ${h1.age} years old, my height is ${h1.height}.")
// Human 2
println("My name is ${h2.name}; and I'm ${h2.age} years old, my height is ${h2.height}.")
The code above will outputs:
My name is John; and I'm 50 years old, my height is 4 feet.
My name is Steve; and I'm 23 years old, my height is 6 feet 2inch
Learn more about Kotlin Object & Classes & Kotlin String Templates.