Kotlin(코틀린)은 JetBrains에서 제작된 프로그래밍 언어로서 구글에서 Android 기본 언어로 채택 되면서 주목받는 hot한 언어가 되었다.
JetBrains의 연구소가 있는 러시아 상트페테르부르크에 있는 코틀린 섬에서 이름을 따왔다고 한다...
본 포스팅에서는 Kotlin에서 Class를 만들고 상속받고 사용하는 방법에 대해서 기술하도록 한다.
먼저 가장 간단하게 Class 만들기
class Animal
중괄호도 필요 없다. 내용은 비었지만-_- 어쨌건 class 는 class다.
그렇다면 Class 사용하는 방법은?
val myAnimal = Animal()
new가 필요 없는 것에 주목.. Kotlin은 class 생성시 new 키워드를 사용하지 않는다.
내용이 비었으니 이제 내용을 채워보자.
Class는 Class 이름, Attribute(member 변수, Property)와 Operation(method)로 구성된다.
먼저 Property를 추가...(Kotlin에서는 Attribute를 Property라고 부른다)
다리갯수(nLeg)와 색깔(color)를 추가하며, type 은 nLeg는 Int, color는 String으로 선언한다.
class Animal {
val nLeg:Int = 4
val color:String = "yellow"
}
Kotlin에서는 class에 기본 getter/setter를 만들어줄 필요가 없다.
val myAnimal = Animal()
println("Number of Leg is ${myAnimal.nLeg}")
println("Color is ${myAnimal.color}")
실행결과는?
Number of Leg is 4 Color is yellow |
IntelliJ에서 Kotlin으로 개발을 하게 되면 Decompiler라는 기능을 통해서 Java로 변경된 code를 확인할 수 있는데, Class에 member만 추가하고 getter/setter가 없어도, Decompiler상에서는 getter/setter가 생성이 된다. 단, val로 선언된 변수의 경우 getter만 생성된다..
Decompiler를 실행하는 방법은 아래 포스팅 참조...
IntelliJ에서 Decompiler를 이용하여 Kotlin을 Java code로 확인하기
IntelliJ에서 Kotlin으로 작성된 소스를 Java 코드로 확인할 수 있다.Decompiler 기능을 이용한 것인데.. Tools > Kotlin > Show Kotlin Bytecode 선택Kotlin Bytecode 탭(?)에서 Decompile 버튼 클릭 Decompile 된 java 소스 확
updatedat.tistory.com
public final class Animal {
private final int nLeg = 4;
@NotNull
private final String color = "yellow";
public final int getNLeg() {
return this.nLeg;
}
@NotNull
public final String getColor() {
return this.color;
}
}
Property가 변경가능 한 값이면 val 대신 var로 선언해주면 된다.
class Animal() {
val nLeg:Int = 4
val color:String = "yellow"
var name:String = "Tom"
}
&아래와 같이 {class 변수 이름}.{property 이름} 으로 접근하고 수정 가능
val myAnimal = Animal()
println("Name of the Animal is ${myAnimal.name}")
myAnimal.name = "Smith"
println("Name of the Animal is ${myAnimal.name}")
실행결과
Name of the Animal is Tom Name of the Animal is Smith |
이번에는 method를 추가해 보자
Anmial Class에 eat()와 cry() method를 추가 한다.
class Animal() {
val nLeg:Int = 4
val color:String = "yellow"
var name:String = "Tom"
fun eat(something:String) {
println("Eat $something")
}
fun cry() {
println("Cry!!!")
}
}
확인해보면...
val myAnimal = Animal()
myAnimal.cry()
myAnimal.eat("apple")
Cry!!! Eat apple |
'MEDIUMTEXT' 카테고리의 다른 글
git에서 merge commit을 revert 하는 방법 (0) | 2024.10.01 |
---|---|
Gson을 이용한 직렬화/역직렬화 (toJson / fromJson) (0) | 2024.09.29 |
git에서 다른 repository에 있는 commit을 cherry-pick 해오는 방법 (0) | 2024.09.28 |
Kotlin class 생성자 정리 (0) | 2024.09.21 |
Gson에서 Json 구성 요소 5가지 (JsonElemnt/JsonObject/JsonPrimitive/JsonArray/JsonNull) (0) | 2024.09.21 |