Kotlin

코틀린 클래스와 객체

Jyuni 2023. 2. 14. 22:41

객체 지향 프로그래밍(OOP : Object Oriented Programming)

  • 프로그램의 구조를 객체 간 상호작용으로 표현하는 프로그래밍 방식
  • 객체와 관계를 표현하며 이를 통해 확장과 재사용성이 용이
  • Java와 Kotlin은 객체 지향 프로그래밍을 지원

클래스

대상들을 분류하고 속성과 함수를 작성한 것

fun main() {
    val coffee = Coffee() // 클래스의 생성자를 통해 객체 생성
    coffee.name = "Latte" // 객체 속성에 값 할당
    coffee.getPrice() // 객체의 함수 호출
}

class Coffee {  // 클래스 작성
    // 속성
    var name: String = "Americano"
    var price: Int = 4000
    // 함수
    fun getPrice() = println("${name} price : ${price}")
}

클래스 생성자

  • 클래스를 통해 객체가 만들어질 때 기본적으로 호출되는 함수
  • 객체를 생성할 때 인자값을 설정할 수 있다.
  • 생성자를 위한 contructor()를 정의할 수 있다.

주 생성자 : 클래스명과 함께 작성하며 가시성지시자나 어노테이션 표기가 없을 경우 contructor 키워드 생략 가능

class Coffee constructor(_name: String, _price: Int) { // 주 생성자
    var name: String = _name
    var price: Int = _price
}
// 주 생성자 초기화 방법
class Coffee1(var name: String = "Americano", var price: Int = 4000) {} // 1. 주 생성자로 속성 기본값 지정
class Coffee2(var name: String, var price: Int) {
    init { // 2. init을 통한 초기화
        name = "Latte"
        price = 5000
    }
}

 

부 생성자 : 클래스 안에 작성하며 하나 이상의 부 생성자를 작성할 수 있다.

class Coffee constructor() {
    var name: String = "Americano"
    var price: Int = 4000

    constructor(_name: String, _price: Int) : this() { // 부 생성자
        this.name = _name
        this.price = _price
    }
}

open 키워드 : 상속을 받기위해 부모 클래스 앞에 open 키워드를 작성해야 한다.

// 상속을 가능하게 부모 클래스 앞에 open 키워드 사용
open class Coffee(var name: String, var price: Int) {
    fun getPrice() = println("${name} coffee : ${price}")
}

// 주 생성자를 사용하는 상속
class Americano(name: String, price: Int): Coffee(name, price){
    fun getCoffeeName() = println("${name}")
}

// 부 생성자를 사용하는 상속
class Latte: Coffee {
    val size: String
    constructor(name: String, price: Int, size: String) : super(name, price) {
        this.size = size
    }
}

super와 this 키워드

  • super : 상위 클래스의 함수, 속성, 생성자를 사용하는 키워드
  • this : 현재 클래스의 함수, 속성, 생성자를 사용하는 키워드

객체

  • 클래스는 선언해도 실제 메모리에 존재하지 않음
  • 객체는 물리적인 메모리 영역에서 실행되는 클래스의 실체