클래스 생성 시 new 키워드 생략
클래스의 멤버변수 반드시 초기화 해야됨
fun main(){
// 객체 생성 : new 키워드 없음
var obj:MyClass = MyClass()
obj.show()
}
class MyClass {
//멤버 변수 - property : 프로퍼티
//코틀린은 멤버변수를 반드시 초기화 해야함
var a:Int = 0
//멤버 함수 - method
fun show(){
println("show : $a")
}
}
🔨 주생성자 생성 방법
class 클래스명 constructor() {
init {
//주 생성자 초기화 블록
}
}
fun main(){
var s = Simple() // 주생성자 자동 호출
}
class Simple constructor() {
//주생성자 초기화용 메소드가 있음
//초기화 블록
init {
println("Simple constructor primary constructor")
}
}
fun main(){
val s2 = Simple2(100, 200, 300)
}
class Simple2 constructor(a:Int, b:Int,var c:Int) {
//주생성자 파라미터에는 var / val 키워드 쓸 수 있음 (원래 파라미터에선 못씀)
//var / val이 있으면 ''파라미터 면서 멤버변수'' 임
var a:Int=0 // 초기화 반드시!!!
init { //주 생성자 초기화 블록
println("Simple2 primary Constructor : $a")
println("Simple2 primary Constructor : $b")
// a를 다른지역 메소드에서도 사용하고 싶으면
// 멤버변수로 만들어서 전달해주기
this.a = a
println("Simple2 primary Constructor : $c") //멤버변수임
}
fun show(){
println("a = $a") //생성자의 매개변수는 메소드에서 사용 불가 -- 생성자로 받은 건 멤버변수로 옮겨야만 쓸수 있다
println("c = $c")
}
}
fun main(){
val s3 = Simple3()
val s4 = Simple3(50) //오버 로딩
}
//보조생성자 - 자바처럼 class 안에 메소드처럼 존재
class Simple3{
//보조 생성자
constructor() {
println("Simple3 보조 생성자")
}
//보조 생성자는 오버로딩 가능
constructor(num:Int) {
println("Simple3 보조 생성자 num : $num")
}
}
fun main(){
//2-3 주생성자와 보조생성자 함께 쓰기
val s5 = Simple4()
val s6 = Simple4(100) //오버로딩 필요 - 보조 생성자 생성
//보조 생성자를 부르면 this() 때문에 주 생성자도 같이 나옴
}
class Simple4 constructor(){
init {
println("simple4 primary constructor")
}
//오버로딩 역할로 보조 생성자 생성
//주생성자와 함께 쓸때는 반드시
//보조 생성자에서 주 생성자의 호출문을 명시적으로 불러야함
//this() 생성자 호출
constructor(num:Int):this() { //this() 필수
//this(); // 자바에선 이자리 맨 위에
println("Simple4 overloding constructor : $num")
}
}
fun main(){
Simple5()
}
class Simple5 () { //constructor 생략
init {
println("simple5 primary constructor")
}
}