객체
- 객체는 식별자(identity), 상태(state), 행동(behavior) 을 가진 실체
클래스
class Product
// 필수 파라미터 지정
class Product constructor(val categoryLabe: String)
// constructor 생성자가 한 개 있을 시 생략 가능
class Product(val categoryLabel: String)
// constructor 생성자가 두 개 이상 일 시 (주 생성자, 부 생성자)
class Product(val categoryLabel: String)
{
constructor(categoryLabel: String, name: String): this(categoryLabel)
}
// 파라미터에 디폴트 값이 존재한다면, categoryLabel 만으로 Product 생성 가능
class Product(val categoryLabel: String, vala name: String = "")
클래스 - 인스턴스 생성 instantiation
- 인스턴스 : 클래스로 만드는 객체
// 생성자 파라미터가 있는 경우
val product = Product("패션", "신발")
// 생성자 파라미터가 없는 경우
class Store{}
val store = Store()
클래스 - 상속 inheritance
- 코틀린 최상위 클래스 : Any
- Any 클래스를 상속받는 하위 클래스는 Any 클래스 (슈퍼 클래스)의 함수, 변수를 접근할 수 있음
- 동시의 여러 슈퍼 클래스를 상속 받을 수 없음
- open 키워드가 붙은 클래스만 상속이 가능
open class Base(p: Int)
class Derived(p: Int) : Base(p)
클래스 - 프로퍼티 property
- 데이터를 저장하는 field + 접근자 (getter / setter)
- getter : field를 호출할 때 값을 반환하는 동작
// displayName 호출 시 categoryLabel과 name으로 값을 만들어 반환
val displayName: String
get() = "$categoryLabel >> $name"
- setter : field를 호출할 때 값을 할당하는 동작
// 새로 입력 받은 값 value 가 0 이상이면 counter에 값 할당
var counter = 0
set(value){
if(value >= 0)
field = value
}
추상 abstract 클래스
- 키워드 abstract 를 추가하여 생성
- 인스턴스화 불가 (객체 생성 불가)
- open 키워드 없이 하위 클래스 상속 가능
- abstract 클래스의 함수는 반드시 하위 클래스에서 구현해야 함
abstract class Polygon{
abstract fun draw()
}
// 오버라이딩을 통한 함수 구현 방식 재정의
class Rectangle : Polygon() {
override fun draw(){
// draw the rectangle
}
}
인터페이스 Interface
- 프로퍼티 정의 가능
- 값을 할당해 상태 저장 불가능
- 프로퍼티의 접근자 getter 제공
- 본문이 있는 함수 정의 가능
- 인터페이스를 상속하는 하위 클래스 생성 가능
- 상속 개수 제한이 없음 -> 하나의 클래스가 동시에 여러 인터페이스를 상속 받을 수 있음
interface MyInterface {
val prop: Int // abstract
val property: String = "property" // Error
val propertyWithImplement: String
get() = "foo"
fun foo() {
print(prop)
}
fun start() // abstract
}
class Child : MyInterface {
override val prop: Int
get() = TODO("Not yet implemented")
override fun start() {
TODO("Not yet implemented")
}
}
728x90
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] Package, 가시성 변경자(public,private,internal,protected) (0) | 2022.09.11 |
---|---|
[Kotlin] 클래스 toString/equals/hashCode, data class (0) | 2022.09.10 |
[Kotlin] 함수, Superclass, Subclass (0) | 2022.09.10 |
[Kotlin] Operator, conditions & loop (0) | 2022.09.06 |
[Kotlin] Variables & Types (0) | 2022.09.06 |