#6 [Kotlin] 클래스, 생성자, 상속

정상준·2022년 10월 28일
0

kotlin

목록 보기
6/26
post-thumbnail

📚클래스와 생성자

📝클래스 선언

class User{ 
   var name = "joung"
   constructor(name : String){ //생성자
    this.name = name
}

  fun someFune(){
      println("name : $name")
}

  class ComeClass{}  //클래스
}

📝클래스 객체 생성 및 접근

val user = User("Joung")
user.someFun

📝주 생성자

코틀린 클래스는 생성자를 주 생성자와 보조 생성자로 구분함. 한 클래스 안에 주 생성자만 선언할 수도 있고 보조 생성자만 선언할 수도 있다. 주 생성자는 constructor키워드로 하며 주 생성자 선언은 필수는 아니며 한 클래스에 하나만 생성 가능

Class User constructor(){
}

or

Class User (){ //constructor 생략가능
}

클래스의 주 생성자를 선언하지 않으면 컴파일러가 매개변수가 없는 주 생성자를 자동으로 추가함

주 생성자의 매개변수

Class User(name : String, count: Int){} //선언

val user = User("Joung",10) //객체 생성

주 생성자의 본문 - init영역

코틀린의 클래스 안에서 init키워드로 지정한 영역은 객체를 생성할 때 자동으로 실행되며 꼭 선언할 필요는 없다. init영역은 일반적으로 주 생성자의 본문을 구현하는 용도로 사용한다.

Class User(name : String, count: Int){
   init{
}

}

📝보조 생성자

보조 생성자는 클래스의 본문에 constructor 키워드로 선언하는 함수이다. 클래스 본문에 선언하므로 여러 개를 추가할 수 있다.

보조 생성자 선언

class User{
   constructor(name : String){
      print("name")
}
   constructor(name : String, count : Int){
     print("name, count")
}
}

클래스를 선언할 때 둘 중 하나만 선언하면 문제가 없지만, 둘 다 선언하면 반드시 생성자끼리 연결해 주어야 한다.

class User(name : String){
   constructor(name : String) : this(name){//주 생성자 호출
      print("name")
}

📝상속

open class Super (name : String){} //상속할 수 있게 open 키워드 이용

class sub (name: String) : Super(name){} // Super를 상속받아 Sub 클래스 선언

상위 클래스를 상속받은 하위 클래스의 생성자에서는 상위 클래스의 생성자를 호출해야 한다.

profile
안드로이드개발자

0개의 댓글