Kotlin 클래스와 객체 (Classes and Objects in Kotlin)
클래스 (Classes)
Kotlin에서 클래스는 class 키워드로 정의됩니다. 클래스는 속성(멤버 변수)과 메서드(멤버 함수)를 포함할 수 있습니다.
기본 클래스 예제:
class Person(val name: String, var age: Int) {
fun speak() {
println("Hello, my name is $name.")
}
}
fun main() {
val person = Person("Alice", 30)
println("Name: ${person.name}, Age: ${person.age}")
person.speak() // 출력: Hello, my name is Alice.
}
생성자 (Constructors)
Kotlin 클래스는 기본 생성자와 부 생성자를 지원합니다. 기본 생성자는 클래스 헤더에 선언되며, 부 생성자는 constructor 키워드로 정의됩니다.
생성자 예제:
class Person(val name: String, var age: Int) {
constructor(name: String) : this(name, 0) {
// 부 생성자
}
}
상속 (Inheritance)
Kotlin은 클래스 상속을 지원하며, open 키워드로 상속 가능한 클래스를 선언합니다. 기본적으로 Kotlin 클래스는 상속이 금지됩니다.
상속 예제:
open class Animal(val species: String) {
open fun makeSound() {
println("Animal makes a sound.")
}
}
class Dog(species: String) : Animal(species) {
override fun makeSound() {
println("Dog barks.")
}
}
객체 (Objects)
Kotlin에서 object 키워드를 사용하여 싱글톤 객체를 정의할 수 있습니다. 싱글톤 객체는 단 하나의 인스턴스만을 가집니다.
싱글톤 객체 예제:
object Logger {
fun log(message: String) {
println("[LOG] $message")
}
}
fun main() {
Logger.log("Logging information.") // 출력: [LOG] Logging information.
}
Kotlin의 클래스와 객체를 이해하면 객체지향 프로그래밍의 개념을 잘 적용할 수 있습니다.
