You are on page 1of 20

Mobile Programming II

Kotlin OOP
• OOP stands for Object-Oriented Programming.
• Object-oriented programming is about creating objects that
contain both data and methods.
• Object-oriented programming has several advantages:
– OOP is faster and easier to execute
– OOP provides a clear structure for the programs
– OOP helps to keep the Kotlin code DRY "Don't Repeat Yourself",
and makes the code easier to maintain, modify and debug
– OOP makes it possible to create full reusable applications with less
code and shorter development time
Kotlin Classes and Objects
• A class is a template for objects, and an object is an
instance of a class.
• To create a class, use the class keyword, and specify the
name of the class.
• For example: in real life, the student has properties, such
as name, department and academic year, and functions,
such as listen and study.
• A property is basically a variable that belongs to the class.
• The object can access properties and functions of a class
by using (.) notation.
Kotlin Classes and Objects
Example:
class Lamp {
// property
var isOn: Boolean = false
// function
fun turnOn() {
isOn = true
}
// function
fun turnOff() {
isOn = false
}
fun displayLightStatus() {
if (isOn == true)
println("lamp is on.")
else
println("lamp is off.")
}
}
Kotlin Classes and Objects
class Lamp {
// property
var isOn: Boolean = false
// function
fun turnOn() {
isOn = true
}
// function
fun turnOff() {
isOn = false
}
fun displayLightStatus() {
if (isOn == true)
println("lamp is on.")
else
println("lamp is off.")
}
}
fun main() {
val lamp = Lamp() // create lamp object of Lamp class
}
Kotlin Classes and Objects
class Lamp {
// property
var isOn: Boolean = false
// function
fun turnOn() {
isOn = true
}
// function
fun turnOff() {
isOn = false
}
fun displayLightStatus() {
if (isOn == true) {
println("lamp is on.")
} else {
println("lamp is off.")
}
}
}
fun main() {
val lamp = Lamp() // create lamp object of Lamp class
print (lamp.displayLightStatus())
} Output: lamp is off.
Kotlin Classes and Objects
class Lamp {
// property
var isOn: Boolean = false
// function
fun turnOn() {
isOn = true
}
// function
fun turnOff() {
isOn = false
}
fun displayLightStatus() {
if (isOn == true) {
println("lamp is on.")
} else {
println("lamp is off.")
}
}
}
fun main() {
val lamp = Lamp() // create lamp object of Lamp class
lamp.turnon()
print (lamp.displayLightStatus()) Output: lamp is on.
}
Kotlin Constructors
A constructor is a concise way to initialize class properties.
It is a special member function that is called when an object is
created.
It is defined by using two parantheses () after the class name.
• Primary constructor - concise way to initialize a class
• Secondary constructor - allows you to put additional
initialization logic
Kotlin Primary Constructors
Example:
class Person(var firstName: String, var age: Int) {
}
fun main() {
val person = Person("Ahmed", 25)
println("First Name = " + person.firstName)
println("Age = " + person.age)
}

class Person(var firstName: String, var age: Int) {


}
fun main() {
val person = Person("Ahmed", 25)
println("First Name = ${person.firstName}")
println("Age = ${person.age}") Output:
} First Name = Ahmed
Age = 25
Kotlin Primary Constructors
To put the initilization code, initializer block is used. It is
prefixed with init keyword.
class Person(fName: String, personAge: Int) {
val firstName: String
var age: Int
// initializer block
init {
firstName = fName
age = personAge

println("First Name = $firstName")


println("Age = $age")
}
}
fun main() {
val person = Person("Ahmed", 25) Output:
} First Name = Ahmed
Age = 25
Default Value in Primary Constructor
class Person(fName: String, personAge: Int=0) {
val firstName: String
var age: Int
// initializer block
init {
firstName = fName
age = personAge

println("First Name = $firstName")


println("Age = $age")
}
}
fun main() {
val person = Person("Ahmed")
}
Output:
First Name = Ahmed
Age = 0
Kotlin Secondary Constructor
class Person {
var firstName: String = ""
var age: Int = 0
constructor (firstname: String, age: Int) {
var fName = firstname
var personAge = age
println("my name is $fName")
println("my age is $personAge")
}
constructor() {
var fName = "Ahmed"
var personAge = 19
println("my name is $fName and my age is $personAge")

}
} Output:
fun main() {
val person1 = Person("Ahmed",25) my name is Ahmed
val person2 = Person() my age is 25
} my name is Ahmed and my age is 19
Kotlin Inheritance
In Kotlin, it is possible to inherit class properties and
functions from one class to another. We group the
"inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from.
Use the open keyword in front of the superclass/parent, to
make this the class other classes should inherit properties and
functions from.
To inherit from a class, specify the name of the subclass,
followed by a colon :, and then the name of the superclass.
Kotlin Inheritance
open class Person (name: String, age: Int) {
init {
println ("My name is $name.")
println ("My age is $age")
}
}
class MathInstructor (name: String, age: Int): Person(name, age) {
fun teachMath() {
println ("I teach in primary school.")
}
}
class Footballer (name: String, age: Int): Person(name, age) {
fun playFootball() {
println ("I play in a club.") Output:
} My name is Ahmed.
}
fun main () {
My age is 25
val person1 = MathInstructor ("Ahmed", 25) I teach in primary school.
person1.teachMath()
println()
My name is Salma.
val person2 = Footballer("Salma", 29)
person2.playFootball() My age is 29
} I play in a club.
Kotlin Inheritance and Overriding
In inheritance, we can provide specific implementation of the
base class functions inside the derived class. It means if a
function exists in parent class then we can provide a different
implementation of the same function in child class. It is
known as Function Overriding.
To override a function, it must be marked as open (just like
the class) in the parent class and in the child class we must
use the keyword override to specify that we have overridden
the function.
The function name and parameters should be same.
Kotlin Inheritance and Overriding
open class Operations {
fun sum (x: Double, y: Double):Double {
return x+y
}
fun sub (x: Double, y: Double):Double {
return x-y
}
}
class SomeOperations : Operations() {
fun mul (x: Double, y: Double):Double {
return x*y
}
}
fun main () {
val op1 = SomeOperations()
println (op1.sub(10.1,5.1))
println (op1.mul(10.1,5.1)) Output:
5.0
} 51.51
Kotlin Inheritance and Overriding
open class Operations {
fun sum (x: Double, y: Double):Double {
return x+y
}
open fun sub (x: Double, y: Double):Double {
return x-y
}
}
class SomeOperations : Operations() {
fun mul (x: Double, y: Double):Double {
return x*y
}
override fun sub (x: Double, y: Double):Double {
return x-y-2
}
}
fun main () {
val op1 = SomeOperations()
println (op1.sub(10.1,5.1))
println (op1.mul(10.1,5.1)) Output:
3.0
} 51.51
Kotlin Inheritance and Overriding
open class Operations {
fun sum (x: Double, y: Double):Double {
return x+y
}
open fun sub (x: Double, y: Double):Double {
return x-y
}
}
class SomeOperations : Operations() {
fun mul (x: Double, y: Double):Double {
return x*y
}
override fun sub (x: Double, y: Double):Double {
println(super.sub(x,y))
return x-y-2
}
}
fun main () { Output:
val op1 = SomeOperations() 5.0
println (op1.sub(10.1,5.1)) 3.0
println (op1.mul(10.1,5.1))
} 51.51
Kotlin Inheritance and Overriding
open class Person() {
open fun getInfo (name:String) {
println ("welcome $name")
}
fun printWelcome () {
println ("welcome")
}
}
class Employee():Person(){
override fun getInfo (jobTitle:String){
super.getInfo ("Ahmed")
println ("your job title : $jobTitle ")
}
}

fun main () {
var person1= Employee()
Output:
person1.getInfo ("Engineer") welcome Ahmed
} your job title : Engineer
Kotlin Inheritance and Overriding
open class Vehicle {
open val color: String = "Black"
open fun printColor() {
println("The color of vehicle is: $color")
}
}
class Jeep: Vehicle() {
override val color: String = "Red"
override fun printColor() {
println("The color of Jeep is: $color")
}
}

fun main() {
val jeep = Jeep()
jeep.printColor()
}

Output:
The color of Jeep is: Red

You might also like