HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
Kotlin docs
Kotlin docs
/
▶️
Classes
▶️

Classes

 
코틀린의 클래스는 class 키워드로 나타냅니다.
 
class Person { /*...*/ }
 
클래스의 선언은 아래의 요소들로 이루어 집니다.
  • 클래스 이름
  • 클래스 헤더
    • 타입 파라미터
    • primary 생성자
    • 다른 것들
  • 클래스 바디
이중 클래스 헤더와 바디는 선택사항입니다.
 
클래스 바디가 없다면 curly braces {} 는 생략 될 수 있습니다.
class Empty
 

생성자

코틀린의 클래스는 primary constructor 주 생성자 와 여러개의 secondary constructors 부 생성자를 가질 수 있습니다.
 

Primary Constructor

주 생성자는 클래스 헤더에 포함되며 클래스의 이름과 선택 사항인 클래스의 타입 파라미터 다음에 나옵니다.
class Person constructor(firstName: String) { /*...*/ }
 
주 생성자에 어노테이션이나 visibility modifiers 가 없다면 constructor 키워드를 생략 할 수 있습니다.
class Person(firstName: String) { /*...*/ }
 
기본 생성나는 코드를 가질 수 없습니다.
초기화 코드는 init 이라는 키워드를 prefix 로 가지는 initializer blocks 안에 위치 할 수 있습니다.
 
코틀린의 주생성자에서 concise syntax (val, var) 한 property 선언을 할 수 있습니다.
class Person(val firstName: String, val lastName: String, var age: Int)
 
기본 값을 가질 수 도 있습니다.
class Person( val firstName: String, val lastName: String, var isEmployed: Boolean = true)
 
클래스의 properties 를 선언 할 때 trailing comma 를 활용할 수 있습니다.
class Person( val firstName: String, val lastName: String, var age: Int, // trailing comma ) { /*...*/ }
 
다른 properties들과 마찬가지로 주생성자의 properties도 mutable(var) 혹은 read-only(val)로 선언 될 수 있습니다.
 
생성자에 어노테이션 혹은 가시성 지정자(Visibility Modifiers) 를 지정하는 경우에는 constructor 키워드를 명시해야 합니다.
class Customer public @Inject constructor(name: String) { /*...*/ }
 

Secondary Constructor

클래스는 constructor prefix 를 가진 부생성자를 가질 수 있습니다.
부생성자는 Java의 생성자와 유사하다. 여러개의 생성자를 만들수 있고 생성자에서 어떤 동작을 할지 정의를 해주어야 한다.  부 생성자임을 알려주는 키워드는 constructor
 
단, 부생성자는 반드시 주생성자와 같이 사용되어야 한다. 부생성자는 주생성자를 호출한다.
 

클래스의 인스턴스화

 
일반 함수 호출 하는 것 처럼 하면 된다.
val invoice = Invoice() val customer = Customer("Joe Smith")
 
코틀린은 new 키워드가 없다.
 

클래스 멤버

  • 생성자와 초기화 블락
  • 함수
  • Properties 속성?
  • Nested and inner classes
  • Object declarations
 

상속

클래스는 서로 derived 될 수 있고 상속 계층을 형성 할 수 있다.
▶️
Inheritance
 

추상 클래스

클래스는 abstract 로선언될 수 있다.
abstract 한 멤버는 구현을 가지지 않는다.
추상 클래스 혹은 함수에 open 을 명시 하지 않아도 된다.
 
abstract class Polygon { abstract fun draw() } class Rectangle : Polygon() { override fun draw() { // draw the rectangle } }
코틀린의 재정의 ovveride 키워드를 확인하자!
 
추상 클래스는 구체 클래스를 상속 받을 수 도 있다.
open class Polygon { open fun draw() { // some default polygon drawing method } } abstract class WildShape : Polygon() { // Classes that inherit WildShape need to provide their own // draw method instead of using the default on Polygon abstract override fun draw() }