Skip to main content

OOP-IN-KOTLIN

Class is a blue print of variables and meathods in it 

There are 5 basic concepts are in Object Oriented Programming(OOP)
    -> Variables and types
    -> Control flows
    -> function
    -> collections
    -> classes and objects ( including inheritence 


 //////////////What is OOPS and Initializers in it and constructors ------------->>

we create a class that includes its members which are variables of different data-types and different functions defined within it called meathods

that class acts like it is a kind of data-type having the operation of the meathod inside it 

class Class_Name ( variableName :DataType = defaultValue(Optional), variableName....){
    class members including class variable and meathods 

}

un main(){
println(">----Program Starts----<\n")
var denis : Person = Person("Denis", "Panjuta" , 31)
var Suppandi : Person = Person("Suppandi", "_", 20)
// var Dvesh : Person = Person(lastName = "Daku")
denis.stateHobby()
denis.hobby = " SkateBorad"
denis.stateHobby()

Suppandi.hobby = " coding "
Suppandi.stateHobby()


println("\n>----Program Terminates-----<")
}

class Person(firstName: String = "Devesh ", lastName :String = "Suthar"){
// note that here firstName variable have default value is a string "Devesh" similarly lastName variable have default value is "Suthar"
// Member Variable- properties
var age: Int? = null // we created the variable to store age for thos age we have for those we dont have will not require space
var hobby: String = " watch Netflix "
var firstName : String? = null
var lastName : String? = null

// Member Function - Methods
fun stateHobby(){
println( "$firstName\'s hobby is $hobby ")
}

// this operator comes in act
// this.variable refers to the variable that is created inside the class
// Initilizer block
init{ // somewhat similar to constructor in c++
this.firstName = firstName
this.lastName = lastName
println("Person Created (Initilizer runs )")
println("Initilization : A new Person Object With firstName = $firstName and lastname = $lastName \nprimary constructor terminates ")
}
// Member Secondary Constructor
constructor(firstName:String, lastName : String , age : Int)
:this ( firstName , lastName){ // means firstName and lastName of this constructor is filled up by variable firstName and lastName of primary constructor
// this age here refers to age variable created in the class gets value of initilization of this constructor
this.age = age
println("Initilizatn : second constructor comes in act \n ")
}

}

This code contain Initilizer which is a meathod named init will run just after the object is created

////////////////Scope And Shadowing ------------------------------>> not very important
just see the code and you will get it 

var b = 7 // scope of this b is everywhere within this file except ther is alredy a local variable with same name
fun main(){
myFunction(5)
var b = 5 // scope of this b is within the main function
}

// This 'a' is a parameter
fun myFunction(a:Int ){
// a = 5 // will be wrong we cannot assign a value to parameter
var a = 5 // this a is our variable
println(" a is $a") // the a will be output will be variable not the paramenter
// now what we have done is we shadowed the 'a' paramenter we no longer can acess that
var b =a // scope of this b is within the myFunction function
println("b is $b")
}

 

/////////////////////////The Getter and Setter ------------------------------>>> 

getter is a funtion that runs just after initilizing a variable that adjudt the value after initlization  

fun main(){
var myCar = Car()
println(myCar.owner)
println("Brand is : ${myCar.myBrand}")
println("MaxSpeed is ${ myCar.maxSpeed}")
println("Model is ${myCar.myModel}")

var hisCar = Car()
hisCar.myBrand = " APPLE "
hisCar.maxSpeed = 200
println("his brand is ${hisCar.myBrand}")
println("his max speed is ${hisCar.maxSpeed}")

}

open class Car() {
lateinit var owner : String // to initilize it on later stage
var myBrand: String = "BMW"
get(){ // custom getter we have created
return field.toLowerCase()
}
var maxSpeed: Int = 250
get() = field
set(value) {
field = if(value > 0 ) value else throw IllegalArgumentException("max speed cannot be less than 0 ")
}
var myModel : String = "M5"
get() = field
private set


// Initilizer variable
init {
this.myModel = "M3"
this.owner = "Frank"
}
}
//2. Backing Field (field)
// Backing field helps you refer to the property
// inside the getter and setter methods.
// This is required because if you use the property
// directly inside the getter or setter then you’ll
// run into a recursive call which will generate
// a StackOverflowError.

 

DATA Classes in Kotlin--------------------------->>

data class User(val id:Long, var name: String ) // just like structure of mutliple type of vaiable forming a new datatype

fun main(){
val user1 = User(1,"Denis")
val name = user1.name
println(name)
//user1.id = 2 // will not be reassigned because it is val
user1.name = "Devesh"
val user2 =User(1, "Devesh")
println(user1 == user2) // which will result in true
println("User Details : $user1")

val updatedUser = user1.copy(name = "Suppandi ")
println(user1)
println(updatedUser)

println(updatedUser.component1()) // print 1
println(updatedUser.component2()) // print suppandi

val (id_, name_ ) = updatedUser // extracting components of a class object to component variable
println("id = $id_ name = $name_")

 

Inheritance ------------------------>>

package com.suppnad1.objectorientedkotline

// The Class that inherits the features of another
// class is called the Sub class or Child class or
// Derived class, and the class whose features are
// inherited is called the Super class or parent class
// or Base class

//// Super class , Parent Class , Base Class
//class Vehicle {
// // properties
// // meathods
//}



// Sub class , child class , or derived class of vehicle
open class CAR( val name: String, val brand: String ) {
open var range: Double = 0.00
fun extendRange(amount:Double){
if (amount>0 )
range += amount
}
open fun drive(distance: Double ){ // First Drive function created by me
println("Drove for $distance KM")
}
}

// sub class , child class or derived class of vehicles
class ElectricCar(name: String, brand: String, batteryLife : Double)
: CAR(name, brand){
var chargerType = "Type1"
override var range = batteryLife * 6
override fun drive(distance: Double){ // Drive function that was orverriden by me
println("Drove for $distance KM on electricity ")
}
fun drive(){ // New Drive function that was created by me
println("Drove for $range KM on electricity_")
}
}

fun main(){
var audiA3 = CAR("A3", "Audi")
var teslaS = ElectricCar("s-model", "Tesla" , 85.5)

teslaS.chargerType = "Type2"

teslaS.extendRange(200.00)

// Var objects inherits f b
teslaS.drive()

//Polymorphism
audiA3.drive(200.00)
teslaS.drive(200.00) // we never implementd function named drive in ecar class

}


Interfaces ___________________>>>>

interface Drivable {
val maxSpeed : Double
fun drive(): String
fun brake(){
println("The drivable is braking")
}
}

// to implement this interface i have to implement its variable and meathod in calss as a overriding way

open class CAR( override val maxSpeed : Double, val name: String, val brand: String ) :Drivable {
open var range: Double = 0.00
fun extendRange(amount:Double){
if (amount>0 )
range += amount
}
open fun drive(distance: Double ){ // First Drive function created by me
println("Drove for $distance KM")
}

// interface
override fun drive():String {
return " Driving the interface Drive "
}

override fun brake(){
super.brake()

}
}

// sub class , child class or derived class of vehicles
class ElectricCar(maxSpeed:Double, name: String, brand: String, batteryLife : Double)
: CAR(maxSpeed, name, brand){
var chargerType = "Type1"
override var range = batteryLife * 6
override fun drive(distance: Double){ // Drive function that was orverriden by me
println("Drove for $distance KM on electricity ")
}
// open fun drive(){ // New Drive function that was created by me
// println("Drove for $range KM on electricity_")
// }
override fun brake(){
super.brake()
println("Breka inside of electric Car")
}
}

fun main(){
var audiA3 = CAR(200.00, "A3", "Audi")
var teslaS = ElectricCar(240.00,"s-model", "Tesla" , 85.5)

teslaS.chargerType = "Type2"

teslaS.extendRange(200.00)

// Var objects inherits f b
teslaS.drive()

//Polymorphism
audiA3.drive(200.00)
teslaS.drive(200.00) // we never implementd function named drive in ecar class

teslaS.brake()
audiA3.brake()
}

 

Abstract Classes ---------------------------------------->>

// An abstract class connot be istantiated ( you cannot create objects of an abstract class.
// however, you can inherit subclasses from an abstract class.
// The member( properties and meathods) of an abstract class are non-abstract
// unless you explicitly use the abstract keyword to make them abstract.

// example
abstract class Mammal( private val name: String, private val origin : String, private val weight: Double){
// ^^^ are concreate (non -abstract ) properties

// Abstreact Property (Must be overridden by SubClasses )
abstract var maxSpeed : Double

// Abstract Meathods (Must be implemented by SubClasses)
abstract fun run()
abstract fun breath()

// Concreate (Non-Abstract) Meathod
fun displayDetails(){
println("Name: $name, Origin: $origin, Weight: $weight, Max Speed : $maxSpeed")
}// we are not limilted to abstract meathods
}

class Human (name:String, origin:String, weight:Double, override var maxSpeed: Double ):Mammal(name,origin,weight){
override fun run (){
println("Run on two legs")
}

override fun breath() {
println("Breath through the mouth and nose ")
}
}
class Elephant(name:String, origin:String, weight:Double, override var maxSpeed: Double ):Mammal(name,origin,weight){
override fun run (){
println("Run on four legs")
}

override fun breath() {
println("Breath through the trunk")
}
}

fun main(){
val human = Human( "Devesh", "India", 70.0, 30.0)
val elephant = Elephant("Rosy", "Russia", 5400.0, 20.0)

// val mammal = Mammal("Denis", "Russia, 29 ,22 ") // cannot create this from a abstract class
human.run()
elephant.run()
human.breath()
elephant.breath()
}

 

hello world


Comments