Kotlin

Kotlin.06 클래스와 프로퍼티

윤태영(Coding) 2023. 4. 2. 08:37
//클래스의 생성자를 만들 때, constructor keyword 사용 가능.
//constructor 생략 가능, 굳이 constructor를 쓰는 경우는, 특정 Annotation을 같이 쓰는 경우.
class Coffee //constructor
  (
  val name:String = "",
  val price: Int = "0",
  val iced : Booelan = false,
  ) {
  
  val brand: String
  //custom getter get() = "스타벅스" //String 표현식 
 get() {
 return "스타벅스"
 }
  //var로 선언된 프로퍼티는 custom setter도 만들 수 있다.
  var quantity : Int = 0
  set(value) {
  if (value > 0) { //수량이 0 이상인 경우에만 할당
  field = value //field는 식별자. setter getter에 사용하게 되면 quantity 같은 이름이 접근한다.
             }
  }
  
  }
  
class EmptyClass

    
fun main() {
  val coffee = Coffee()
  coffee.name = "아이스 아메리카노"
  coffee.price = 2000
  coffee.quantity = 1 
  coffee.iced = true
    
  if(coffee.iced) { 
    println("아이스 커피")
  }  //아이스커피    
  println("${coffee.brand} ${coffe.name} 가격은 ${coffee.price} 수량은 ${coffee.quantity}")
 //스타벅스 아이스 아메리카노 가격은 2000 수량은 1
}

출처 : FastCampus