Kotlin is Object Oriented Programming language and it has all features of OOP.
It also supports functional programming like lambdas and higher-order functions.
since its Object Oriented so we have Classes in Kotlin, and those Classes have Objects, which are instances of Classes in Kotlin.
In this article, we will cover:-
Let us first understand what are Classes in Kotlin.
A Class in Kotlin is a user-defined data type which can have properties and member functions inside the body of a Class.
To declare a class in Kotlin
we simply write class <Keyword> ClassName<Name of the Class>
class ClassName {
// inside body of a class, we can declare:
// properties
// member functions
}
A Class in Kotlin can have following members:
Let’s take an example of a Vehicle class.
Like any other OOP language Classes in Kotlin can have properties like the number of doors, engine type, mileage covered and member functions.
Kotlin does not have fields in Classes.
Classes in Kotlin only allows properties.
class Vehicle {
// properties or members of Vehicle class in Kotlin
var doors: Int = 4
var engineType: Int = 1
var mileage: Int = 500
// member functions of class
fun stopCar() {
// stop car implementation goes here...
}
fun startCar() {
// start car implemntation goes here...
}
}
In above code example, we used class keyword to declare a class in Kotlin.
As you might have noticed that I have initialized properties of our Vehicle class in above code example.
var doors: Int = 4
var engineType: Int = 1
var mileage: Int = 500
If we do not initialize properties like above, the compiler will give us an error message.
Properties in class must be initialized or declared abstract.
To access properties and member functions of a class, we need an object of a Class.
An object contains all the information for a Class.
Note:-
No memory is allocated when you define a Class.
Memory is allocated only when you initialize an object of a class in Kotlin.
> Also there is no new keyword in Kotlin.
> You just have to write name of the class to initialize instance of class in Kotlin.
This is how we initialize a class and access its properties and member functions.
fun main(args: Array<String>) {
// vehicle1 is an Object of our Vehicle class.
var vehichle1 = Vehicle()
vehichle1.engineType = 100
vehichle1.startCar()
var vehicle2 = Vehicle()
vehicle2.engineType = 200
vehicle2.startCar()
}
We initialized Vehicle class by calling its default constructor as if it were a regular function.
We can access member functions and properties of Kotlin Classes, using dot (.) notation in Kotlin.
I want to initialize those values when creating an object of a class.
As each object will have its own properties so their values should be initialized while creating an object of a class.
Now we will add a constructor to our Vehicle class.
class Vehicle (initDoors: Int, initEngineType: Int, initMileage: Int){
// properties or members of Vehicle class in Kotlin
var doors:Int = initDoors
var engineType:Int = initEngineType
var mileage: Int = initMileage
// member functions of class
fun stopCar() {
// stop car implementation goes here...
}
fun startCar() {
// start car implemntation goes here...
}
}
Now we will initialize class properties through constructor while creating an instance of a class.
This is how we initialize a class and access its properties and member functions.
fun main(args: Array<String>) {
// vehicle1 is an Object of our Vehicle class.
// passing properties values while creating object of a class.
var vehichle1 = Vehicle(4, 1, 100)
}
Now class properties are not initialized by default instead, properties will be initialized when we will create an instance of a class.
I recommend you go through Data classes in Kotlin.
An interface is similar to Class but it is used to specify behavior a Class must implement.
Interface allows code reusability.
An interface in Kotlin can contain declaration of abstract method and method implementation.
interface IExample1 {
// abstract method
fun doSomething()
// method with implementation
fun doSomethingElse() {
}
var prop: String // abstract property
val properyWithImplementation :String
get() = "interface propery with implementation"
}
In above code example interface IExample1 is defined and it has
Two properties (one abstract and one with its own implementation)
Two methods (one abstract and one with its own implementation)
interface IExample1 {
// abstract method
fun doSomething()
// method with implementation
fun doSomethingElse() {
println("hello kotlin interface example")
}
var prop: String // abstract property
val properyWithImplementation :String
get() = "interface propery with implementation"
}
class Child : IExample1 {
override fun doSomething() {
println("abstract method implemented by class implementing interface")
}
override var prop: String
get() = "abstract property overrided by accessor here"
set(value) {}
}
fun main(args: Array<String>) {
var child = Child()
println(child.properyWithImplementation)
child.doSomethingElse()
child.doSomething()
println(child.prop)
}
The output of the above program will be
interface propery with implementation
hello kotlin interface example
abstract method implemented by class implementing interface
abstract property overrided by accessor here
In java if we want to declare a class which cannot be inherited by any other class we mark it as Final using “final” keyword. By default all classes can be inherited in Java.
But in Kotlin by default all classes are final (cannot be inherited by default).
class Base {
}
class Derived : Base() {
}
If you write above code you will get compile time error “This type is final, so it cannot be inherited”.
If we want to specify a Class which can be inherited we use “open” keyword.
open class Base {
}
class Derived : Base() {
}
Now you will not get this type is final error.
fun main(args: Array<String>) {
var derived = Derived()
derived.addTwoNumbers()
}
open class Base {
open fun addTwoNumbers() {
println("base class function")
}
}
class Derived : Base() {
override fun addTwoNumbers() {
super.addTwoNumbers()
println("derived class function")
}
}
If you run the above program it will print following output:
base class function
derived class function
Classes in Kotlin can be declared abstract similar to Java using “abstract” keyword.
If you want derived class to provide its own method implementation you can declare Class as abstract and mark its member function as abstract.
An abstract class cannot be initialized similar to Java.
An abstract member function does not provide its own implementation instead Class which derived from abstract Class override abstract method and provides implementation.
fun main(args: Array<String>) {
var secondDerived = SecondDerived()
secondDerived.addTwoNumbers()
}
abstract class Derived {
abstract fun addTwoNumbers()
}
class SecondDerived : Derived() {
override fun addTwoNumbers() {
println("this class will provide its own method implementation")
}
}
If you run this program you will get output:
this class will provide its own method implementation.
Kotlin Programming language idioms Tutorial with code examples
How to Develop Android Image Gallery App using Kotlin – Tutorial with Complete Source Code