Kotlin class, 2024-03-18

sunj - Mar 18 - - Dev Community
class Human constructor(name : String){
   val name = name
   fun eating(){
      println("YUMMMMMYYYY")
   }
}

fun main(){
   val human = Human("example")
   human.eating()

   println("this human's name is ${human.name}")
}
Enter fullscreen mode Exit fullscreen mode
class Human (val name : String){
   fun eating(){
      println("YUMMMMMYYYY")
   }
}

fun main(){
   val human = Human("example")
   human.eating()

   println("this human's name is ${human.name}")
}
Enter fullscreen mode Exit fullscreen mode

같다

class Human (val name : String = "defalut"){
   fun eating(){
      println("YUMMMMMYYYY")
   }
}

fun main(){
   val human = Human() // 디폴트 값을 줘서 생성 가능
   human.eating()

   println("this human's name is ${human.name}")
}
Enter fullscreen mode Exit fullscreen mode
class Human (val name : String = "defalut"){
   init{
     println("New human has been born!")
  }

   fun eating(){
      println("YUMMMMMYYYY")
   }
}

Enter fullscreen mode Exit fullscreen mode

init 인스턴스 생성 시 어떤 동작을 하길 원하는 것을 적어줄 수 있음 / 주 생성자이기 때문에 가장 먼저 실행

//주 생성자
class Human (val name : String = "defalut"){
   //부 생성자
   constuctor(name : String, age : Int) : this(name){
      println("my name is  ${name}, ${age}years old")
   }

   init{
     println("New human has been born!")
  }

   fun eating(){
      println("YUMMMMMYYYY")
   }
}

Enter fullscreen mode Exit fullscreen mode
open class Human (val name : String = "defalut"){
   constuctor(name : String, age : Int) : this(name){
      println("my name is  ${name}, ${age}years old")
   }

   init{
     println("New human has been born!")
  }

   fun eating(){
      println("YUMMMMMYYYY")
   }

   fun sing(){
      println("Laralll")
   }

}


class Korean : Human(){
   override fun sing(){
      super.sing()
      println("라랄라랄")
   }
}

fun main(){
   val korean = Korean()
   korean.sing()
}
Enter fullscreen mode Exit fullscreen mode

코틀린은 기본적으로 파이널 클래스를 가지고 있다. 그렇기 때문에 open을 붙여줘야 한다. 오버라이드를 할 때도 같다

super을 붙여주면 부모를 그대로 가져올 수 있다
상속은 하나밖에 못한다

참조 : Code with Joyce

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player