[Kotlin] 3장 객체 지향 프로그래밍

1. 클래스 및 객체

코틀린(Kotlin)은 현대적인 객체 지향 프로그래밍(OOP)언어로, 클래스, 객체, 상속, 다형성, 인터페이스, 추상 클래스 등의 개념을 지원합니다. 먼저 클래스 및 객체를 알아보도록 하겠습니다. 클래스는 객체를 생성하기 위한 템플릿으로 객체는 클래스의 인스턴스입니다.

// 클래스 정의
class Person(val name: String, var age: Int) {
    fun introduce() {
        println("Hello, My Name is ${name}, age is $age years old")
    }
}

// 객체 생성
fun main() {
    val person = Person("James", 30)
    person.introduce() // "Hello, My Name is James, age is 30 years old
}

2. 상속

상속은 기존 클래스(부모 클래스)의 속성과 메서드를 새로운 클래스(자식 클래스)가 물려받는 것입니다.

open class Animal (val name: String) {
    open fun sound() {
        println("동물이 소리를 냄")
    }
}

class Dog(name: String) : Animal(name) {
    override fun sound() {
        println("$name: 멍멍!")
    }
}

fun main() {
    val dog = Dog ("백구")
    dog.sound(); // "백구: 멍멍!"
}

3. 다형성

다형성은 같은 이름의 메서드를 사용하나, 객체에 따라 다른 동작을 하는 것을 의미합니다. 이는 주로 상속과 오버라이딩을 통해 구현됩니다.

fun makeSound(animal: Animal) {
    animal.sound()
}

fun main() {
    val dog = Dog("백구")
    makeSound(dog)  // "백구: 멍멍!"
}

4. 인터페이스

인터페이스는 클래스가 구현해야 하는 메서드의 집합을 정의하며, 인터페이스는 다중 상속을 지원합니다.

interface Drivable {
    fun drive()
}

class Car : Drivable {
    override fun drive() {
        println("Car is Running!")
    }
}

fun main() {
    val car = Car()
    car.drive() // "Car is Running"
}

5. 추상 클래스

추상 클래스는 인스턴스화할 수 없는 클래스이며, 자식 클래스에서 반드시 구현해야 할 메서드를 정의할 수 있습니다.

abstract class Shape {
    abstract fun area(): Double
}

class Rectangle(val width: Double, val height: Double) : Shape() {
    override fun area(): Double {
        return width * height
    }
}

fun main() {
    val rectangle = Rectangle(5.0, 3.0)
    println("사각형의 면적: ${rectangle.area()}") // "사각형의 면적: 15.0"
}

 

 

GitHub - Koras02/kotlin-blogin: https://thinky.tistory.com/category/Mobile/Kotlin

https://thinky.tistory.com/category/Mobile/Kotlin. Contribute to Koras02/kotlin-blogin development by creating an account on GitHub.

github.com

 

LIST

'Mobile > Kotlin' 카테고리의 다른 글

[Kotlin] 5장 안드로이드 개발 세팅  (0) 2025.03.18
[Kotlin] 4장 고급 기능  (0) 2025.03.08
[Kotlin] 2장 기초문법  (0) 2025.02.24
[Kotlin] 1장.Kotlin이란?  (1) 2025.02.23