So far we have seen only the functional style of programming in Kotlin. In this article, you will learn that Kotlin is also an object-oriented programming language. In object-oriented programming, the complex problem is separated into smaller subsets of objects where these objects interact with each other to perform their tasks. Let’s explore what are classes and objects.
Class
Class is the user-defined template that represents the real-life entities which consist of a set of states (member properties) and behaviors (member functions/ methods). For example, a Calculator can be a class, which has two operands and an operator as its properties and performCalculation() as its function.
class Calculator {
val operand1 = 12
val operand2 = 11
val operator = '+'
fun performCalculation(): Int {
return when (operator) {
'+' -> operand1 + operand2
'-' -> operand1 - operand2
'*' -> operand1 * operand2
'/' -> operand1 / operand2
else -> operand1 + operand2
}
}
}
Class is like a blueprint or a template to represent an entity of the real world. The class helps us to have an organized way of defining and describing data and procedures in our code. Let’s see another example of a class.
class Car {
val carModel = "xyz"
val color = "transparent"
fun drive(distance: Int) {
println("You just drove $distance kilometers in your $carModel car")
}
}
Object
An object is an instance of a class. To use the properties and functions of a class, we create an object. If we take the same example where we had a class named Car than BMW, Mercedes, Toyota are our instances or objects. Each of these objects shares the same member or functions of their class.
class Car {
val carModel = "xyz"
val color = "transparent"
fun drive(distance: Int) {
println("You just drove $distance kilometers in your $carModel car")
}
}
fun main(args: Array<String>) {
val bmw = Car()
bmw.drive(250)
val mercedes = Car()
mercedes.drive(300)
}
In line 11 and 14, we have created the two objects bmw and mercedes. These two objects share the same behavior and properties e.g drive but with different identities.
In the next articles, you will learn more about what can we do with classes and what happens when an object is created.
No responses yet