Object Oriented Programming
- A programming paradigm that uses the concept of classes and objects
- Four main Principles of Programming Encapsulation, Inheritance, Abstraction
and Polymorphism.
Class and Object
- Class is the blueprint of the object
- The class and the class file is recommended to have the same class name
Creating a Class
class NameOfTheClass {
var parameter1: Int = 20
var parameter2: Int = 30 // → Properties
var parameter3: String = "Master"
fun nameOfTheFunction() {
println("This is a function") // → Function or Behaviour
}
}
Refining an object using a Class
fun main() {
val variable = NameOfTheClass() // → Creating an instance of the class
variable.parameter1 = 10 // → Changing the value of the property
println("parameter1: ${variable.parameter1}") // → Accessing the property
println("parameter2: ${variable.parameter2}")
println("parameter3: ${variable.parameter3}")
[Link]() // → Accessing the function
// Note: There are no getter functions defined for properties, so we access them
directly.
println("parameter1: ${variable.parameter1}")
println("parameter2: ${variable.parameter2}")
}
Getters and Setters
- Setter is used to set the value of any variable
- Getter is used to get the value
class NameOfTheClass {
var parameter1: Int = 20
var parameter2: Int = 30
val add
get() = parameter1 + parameter2 // → Getters
var name: String = "Name"
set(value) {
if ([Link] == 0) {
println("It is empty!") // → Setters
} else {
field = value
}
}
}
fun main() {
val variable = NameOfTheClass() // → Creating an instance of the class
println("Add: ${[Link]}") // → Calling the Getters
[Link] = "Master" // → Calling the Setters
println("The Name is ${[Link]}")
}
Visibility Modifiers
*public - default, can be be accessed everywhere
*internal - available everywhere in the same module
*private - available only inside the containing file or class
*protected - same as private but available inside the sub class or child classes
Constructors and init block
- Constructor is a concise way to initialize class properties
*Class to Object
class NameOfTheClass(var parameter1: String, var parameter2: Int) {
init {
println("This is Init Block")
// You can create logic for the constructor here if needed
}
}
fun main() {
// → Declaring the value of the constructor using positional arguments
val variableName = NameOfTheClass("Master", 19)
// → Declaring the value of the constructor using named arguments
val anotherVariableName = NameOfTheClass(parameter1 = "Master", parameter2 =
19)
// Accessing the values of parameter1 and parameter2 for each instance
println(variableName.parameter1) // Output: Master
println(variableName.parameter2) // Output: 19
}
Inheritance
- Main features of any object oriented programming languages
- Creating another class using existing class
open class ParentClass(private val name: String, private val age: Int) {
fun firstClassFunction() {
println("This is the First Class!")
}
}
// With this colon, you can inherit the class
class ChildClass(private val name: String, private val age: Int) : ParentClass(name, age)
{
fun secondClassFunction() {
println("This is the Second Class!")
}
}
fun main() {
val inheritClass = ChildClass("Master", 19)
[Link]()
[Link]()
}
Polymorphism
- considered one of the important features of Object-Oriented Programming
- allows us to perform a single action in different ways.
- allows you to define one interface and have multiple implementations
- word “poly” means many and “morphs” means forms, So it means many forms
- Types of polymorphism Compile-time Polymorphism & Runtime Polymorphism
*Runtime Polymorphism
- the compiler resolves a call to overridden/overloaded methods at runtime
- You can achieve run-time polymorphism using method overriding
open class Sup{
open fun method1(){
println("printing method 1 from inside Sup")
}
fun method2(){
println("printing method 2 from inside Sup")
}
}
class Sum:Sup(){
override fun method1(){
println("printing method 1 from inside Sum")
}
}
fun main(args: Array<string>){
var a = Sup()
a.method1()
a.method2()
var b = Sum()
b.method1() b.method2()
}
*Compile-time Polymorphism
- the name functions, that is, the signature remains the same but parameters or
return type is different
- the compiler then resolves which functions we are trying to call based on the type
of parameters and more
fun main() {
println(doubleOf(4))
println(doubleOf(43f))
}
// This function takes an Int 'a' as input and returns the result of '2 + a'.
fun doubleOf(a: Int): Int {
return 2 + a
}
// This function takes a Float 'a' as input and returns the result of '2 + a'.
fun doubleOf(a: Float): Float {
return 2.0f + a
}
Abstract
- just defining members of the functions of a class without the actual
implementation
- a class that cannot be instantiated and is meant to be subclassed
- It contains both abstract methods (methods without a body) and concrete
methods (methods with a body).
- used to provide a common interface and implementation for its subclasses
- can not instantiate means we can not create object for the abstract class
*Abstract class
abstract class Student(val name: String,val level: Int) { // Non-Abstract
// Property
// Abstract Property (Must be overridden by Subclasses)
abstract var salary: Double
// Abstract Methods (Must be implemented by Subclasses)
abstract fun dateOfBirth(date:String)
// Non-Abstract Method
fun employeeDetails() {
println("Name of the employee: $name")
println("Experience in years: $level")
println("Annual Salary: $salary")
}
}
// derived class
class IT(name: String,level: Int) : Student(name,level) {
override var salary = 1000.00
override fun dateOfBirth(date:String){
println("Date of Birth is: $date")
}
}
fun main() {
val it = IT("Master",2)
[Link]()
[Link]("March 11, 2004")
}
Encapsulation
- allows the internal representation and behavior of an object to be hidden from the
outside world or in short it is use for code security. It also similar to Abstraction
class MySpeedInReplying {
private var speed: Int = 0
private val maxSpeed: Int = 200
fun accelerate(increment: Int) {
speed += increment
if (speed > maxSpeed) {
speed = maxSpeed
}
}
fun getSpeed(): Int {
return speed
}
}
fun main() {
val myReply = MySpeedInReplying()
[Link](50)
// Error: Cannot access 'speed': it is private in ’MySpeedInReplying’'
// println([Link])
// Accessing the speed through the public method getSpeed()
println([Link]()) // Output: 50
}
-Master