0% found this document useful (0 votes)
18 views7 pages

Kotlin OOP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

Kotlin OOP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

// Simple class definition

class Person {
var name: String = ""
var age: Int = 0

fun introduce() {
println("Hi, I'm $name and I'm $age years old")
}

fun haveBirthday() {
age++
println("Happy birthday! I'm now $age years old")
}
}

// Class with primary constructor


class Student(val name: String, val studentId: String) {
var gpa: Double = 0.0

// init block runs when object is created


init {
println("Created student: $name with ID: $studentId")
}

// Secondary constructor
constructor(name: String, studentId: String, initialGpa: Double) : this(name,
studentId) {
this.gpa = initialGpa
println("Set initial GPA to $initialGpa")
}

fun study(subject: String) {


println("$name is studying $subject")
}

fun displayInfo() {
println("Student: $name, ID: $studentId, GPA: $gpa")
}
}

fun main() {
// Creating objects
val person1 = Person()
person1.name = "Alice"
person1.age = 25
person1.introduce()
person1.haveBirthday()

// Using constructor
val student1 = Student("Bob", "STU001")
student1.gpa = 3.5
student1.displayInfo()
student1.study("Kotlin Programming")

// Using secondary constructor


val student2 = Student("Carol", "STU002", 3.8)
student2.displayInfo()
}
=======================================

class BankAccount(initialBalance: Double) {


// Property with custom getter and setter
var balance: Double = initialBalance
get() {
println("Checking balance...")
return field
}
set(value) {
if (value >= 0) {
field = value
println("Balance updated to $$value")
} else {
println("Cannot set negative balance!")
}
}

// Read-only property with custom getter


val isRich: Boolean
get() = balance > 1000000

// Property with backing field


var accountHolder: String = ""
set(value) {
field = value.trim().uppercase()
}

fun deposit(amount: Double) {


if (amount > 0) {
balance += amount
println("Deposited $$amount")
}
}

fun withdraw(amount: Double): Boolean {


return if (amount > 0 && balance >= amount) {
balance -= amount
println("Withdrew $$amount")
true
} else {
println("Insufficient funds or invalid amount")
false
}
}
}

// Class with computed properties


class Rectangle(val width: Double, val height: Double) {
val area: Double
get() = width * height

val perimeter: Double


get() = 2 * (width + height)

val isSquare: Boolean


get() = width == height
fun displayInfo() {
println("Rectangle: ${width}x${height}")
println("Area: $area, Perimeter: $perimeter")
println("Is square: $isSquare")
}
}

fun main() {
val account = BankAccount(1000.0)
account.accountHolder = " john doe "
println("Account holder: ${account.accountHolder}")

account.deposit(500.0)
println("Current balance: ${account.balance}")
println("Is rich? ${account.isRich}")

account.withdraw(200.0)
account.balance = -100.0 // This will be rejected

println("\n=== Rectangle Example ===")


val rect = Rectangle(5.0, 3.0)
rect.displayInfo()

val square = Rectangle(4.0, 4.0)


square.displayInfo()
}

====================================

// Base class (must be marked 'open' to allow inheritance)


open class Animal(val name: String) {
open val species: String = "Unknown"

init {
println("Animal created: $name")
}

open fun makeSound() {


println("$name makes a generic animal sound")
}

open fun eat(food: String) {


println("$name eats $food")
}

// Final method (cannot be overridden)


fun sleep() {
println("$name is sleeping")
}
}

// Derived class
class Dog(name: String, val breed: String) : Animal(name) {
override val species: String = "Canis familiaris"

override fun makeSound() {


println("$name barks: Woof! Woof!")
}
override fun eat(food: String) {
println("$name happily eats $food with tail wagging")
}

// Additional method specific to Dog


fun fetch() {
println("$name fetches the ball")
}
}

class Cat(name: String, val color: String) : Animal(name) {


override val species: String = "Felis catus"

override fun makeSound() {


println("$name meows: Meow! Meow!")
}

fun climb() {
println("$name climbs the tree")
}
}

// Abstract class example


abstract class Vehicle(val brand: String) {
abstract val maxSpeed: Int
abstract fun start()

// Concrete method
fun displayBrand() {
println("This is a $brand vehicle")
}
}

class Car(brand: String, override val maxSpeed: Int) : Vehicle(brand) {


override fun start() {
println("$brand car engine started")
}

fun honk() {
println("Beep beep!")
}
}

fun main() {
val dog = Dog("Buddy", "Golden Retriever")
println("Species: ${dog.species}")
dog.makeSound()
dog.eat("dog food")
dog.fetch()
dog.sleep()

println()

val cat = Cat("Whiskers", "Orange")


cat.makeSound()
cat.eat("fish")
cat.climb()

println()
// Polymorphism - treating different objects the same way
val animals: List<Animal> = listOf(
Dog("Rex", "German Shepherd"),
Cat("Mittens", "Black"),
Dog("Luna", "Husky")
)

println("=== Animal Sounds ===")


for (animal in animals) {
animal.makeSound() // Calls the appropriate overridden method
}

println()
val car = Car("Toyota", 180)
car.displayBrand()
car.start()
car.honk()
}

=======================================

fun main() {
println("=== LISTS ===")

// Immutable list
val fruits = listOf("apple", "banana", "cherry")
println("Fruits: $fruits")
println("First fruit: ${fruits[0]}")
println("Contains banana: ${fruits.contains("banana")}")

// Mutable list
val mutableFruits = mutableListOf("apple", "banana")
mutableFruits.add("cherry")
mutableFruits.remove("banana")
println("Modified fruits: $mutableFruits")

println("\n=== SETS ===")

// Set (unique elements)


val uniqueNumbers = setOf(1, 2, 3, 2, 1, 4)
println("Unique numbers: $uniqueNumbers") // [1, 2, 3, 4]

val mutableSet = mutableSetOf("kotlin", "java", "python")


mutableSet.add("swift")
println("Programming languages: $mutableSet")

println("\n=== MAPS ===")

// Map (key-value pairs)


val countryCapitals = mapOf(
"USA" to "Washington D.C.",
"France" to "Paris",
"Japan" to "Tokyo"
)

println("Capital of France: ${countryCapitals["France"]}")

val mutableGrades = mutableMapOf<String, Int>()


mutableGrades["Alice"] = 95
mutableGrades["Bob"] = 87
mutableGrades["Carol"] = 92

for ((student, grade) in mutableGrades) {


println("$student: $grade")
}
}

=========================================

fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

println("=== BASIC LAMBDAS ===")

// Lambda syntax: { parameter -> expression }


val isEven = { number: Int -> number % 2 == 0 }
println("Is 4 even? ${isEven(4)}")
println("Is 5 even? ${isEven(5)}")

// Using lambdas with collections


val evenNumbers = numbers.filter { it % 2 == 0 }
println("Even numbers: $evenNumbers")

val doubledNumbers = numbers.map { it * 2 }


println("Doubled numbers: $doubledNumbers")

val sum = numbers.reduce { acc, number -> acc + number }


println("Sum: $sum")

println("\n=== PRACTICAL LAMBDA EXAMPLES ===")

// Working with strings


val names = listOf("alice", "bob", "charlie", "diana")
val capitalizedNames = names.map { it.replaceFirstChar { char ->
char.uppercase() } }
println("Capitalized names: $capitalizedNames")

// Filtering with complex conditions


val longNames = names.filter { it.length > 4 }
println("Long names: $longNames")

// Finding elements
val firstLongName = names.find { it.length > 5 }
println("First long name: $firstLongName")

// Checking conditions
val allNamesShort = names.all { it.length < 10 }
val anyNameStartsWithA = names.any { it.startsWith("a") }
println("All names short: $allNamesShort")
println("Any name starts with 'a': $anyNameStartsWithA")

println("\n=== HIGHER-ORDER FUNCTIONS ===")

// Function that takes another function as parameter


fun processNumbers(numbers: List<Int>, operation: (Int) -> Int): List<Int> {
return numbers.map(operation)
}
val squares = processNumbers(numbers) { it * it }
val cubes = processNumbers(numbers) { it * it * it }

println("Squares: $squares")
println("Cubes: $cubes")

// Function that returns a function


fun createMultiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}

val doubler = createMultiplier(2)


val tripler = createMultiplier(3)

println("Double 5: ${doubler(5)}")
println("Triple 5: ${tripler(5)}")
}

You might also like