Kotlin _3

### class

class User {
    var name = "Me!"
    fun sayHi(){
        println("hi $name")
    }
}

fun main(args: Array<String>){
	val user = User()
    println(user.name)
    user.sayHi()
    
    user.name = "steve"
    println(user.name)
    user.sayHi()  
}

constructor
->classの引数の渡し方はmethodと同様に型を指定する

class User(var name: String) { // constructor
    var team = "red"
    init {
        println("instance created: name: $name, team: $team")
    }
    fun sayHi(){
        println("hi $name")
    }
}

fun main(args: Array<String>){
	val tom = User("tom")
    println(tom.name)
    tom.sayHi()
}

instance created: name: tom, team: red
tom
hi tom

### getter, setter

    // getter
//     get(){
//         return field.toUpperCase()
//     }
    get() = field.toUpperCase()
    // setter
    set(value) {
        if(value != ""){
            field = value
        }
    }

### override
継承される側はopenを付ける

class AdminUser(name: String): User(name){
    fun sayHello(){
        println("hello $name")
    }
    override fun sayHi(){
        println("[admin] hi $name")
    }
    
}

open class User(var name: String){
    open fun sayHi(){
        println("hi $name")
    }
}

fun main(args: Array<String>) {
    val bob = AdminUser("bob")
    println(bob.name)
    bob.sayHello()
    bob.sayHi()
}

### アクセス修飾子
public:どこからでも、protected: そのクラス+サブクラス、private:そのクラスのみ
-> アクセスをcontrollすることで安全なプログラムを書ける

### 拡張

fun User.sayHi(){
    println("[ext] hello $name")
}

val User.myName: String
 get() = "I am $name"

open class User(var name: String){
    fun sayHi(){
        println("hi $name")
    }
}

fun main(args: Array<String>) {
    val bob = User("bob")
    println(bob.name)
    bob.sayHi()
}

### 抽象クラス・具象クラス
抽象クラスはabstractとする

abstract class User{
    abstract fun sayHi()
}

class Japanese: User() {
    override fun sayHi(){
        println("こんにちは!")
    }
}

class American: User() {
    override fun sayHi(){
        println("Hi!")
    }
}


fun main(args: Array<String>) {
	val tom = American()
    val aki = Japanese()
    tom.sayHi()
    aki.sayHi()
}

### Interface
抽象プロパティ、抽象メソッド、メソッド

interface Sharable {
    val version: Double
    fun share()
    fun getInfo(){
        println("Share I/F ($version)")
    }
}

class User: Sharable {
    override val version = 1.1
    override fun share(){
        println("Sharing ...")
    }
}

fun main(args: Array<String>) {
	val user = User()
    user.share()
    user.getInfo()
}