0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Kotlin】オブジェクト指向基礎

Posted at

はじめに

Kotlin はオブジェクト指向をベースにしつつ、関数型の要素も取り入れたモダンな言語です。
この記事では クラスとオブジェクトの基本 を整理します。


1. クラスとオブジェクト

Kotlinのクラス定義はシンプルです。

class Person(val name: String, var age: Int)

fun main() {
    val p = Person("Anna", 21)
    println("${p.name} is ${p.age} years old")
}
  • val → 読み取り専用プロパティ
  • var → 読み書き可能プロパティ

2. コンストラクタ

Kotlinには プライマリコンストラクタセカンダリコンストラクタ があります。

プライマリコンストラクタ

class User(val name: String, val age: Int)

init ブロック

初期化処理を追加できます。

class User(val name: String, val age: Int) {
    init {
        println("User created: $name ($age)")
    }
}

セカンダリコンストラクタ

class User(val name: String) {
    var age: Int = 0

    constructor(name: String, age: Int): this(name) {
        this.age = age
    }
}

3. プロパティとカスタムアクセサ

Kotlinのプロパティはデフォルトで getter/setter を持ちます。
必要に応じてカスタマイズ可能です。

class Rectangle(val width: Int, val height: Int) {
    val area: Int
        get() = width * height   // カスタム getter

    var name: String = "Rect"
        set(value) {
            field = value.uppercase() // setter をカスタマイズ
        }
}

4. 可視性修飾子

Kotlinのアクセス修飾子は次の通り:

  • public(デフォルト):全てに公開
  • internal:同一モジュール内でのみ公開
  • protected:クラスとサブクラスからアクセス可能
  • private:同一クラス内のみ
class Example {
    private val secret = "hidden"
    protected val semiSecret = "subclass ok"
    internal val moduleOnly = "same module"
    val normal = "public"
}

5. 特殊なクラス

Data クラス

データ保持用。equals, hashCode, toString, copy が自動生成されます。

data class User(val id: Int, val name: String)

val u1 = User(1, "Anna")
println(u1)  // User(id=1, name=Anna)

Enum クラス

列挙型を表現できます。

enum class Direction {
    NORTH, SOUTH, EAST, WEST
}

val d = Direction.NORTH

Object 宣言(シングルトン)

クラスを1つだけインスタンス化したいときに利用。

object Database {
    fun connect() = println("Connected")
}

Database.connect()

Companion Object

Java の static メンバーに相当。クラスごとに1つ存在します。

class Config {
    companion object {
        const val VERSION = "1.0"
        fun printVersion() = println("Version: $VERSION")
    }
}

Config.printVersion()

まとめ

  • クラスとオブジェクト:シンプルに定義できる
  • コンストラクタ:プライマリ + セカンダリ、init で初期化
  • プロパティ:getter/setter をカスタマイズ可能
  • 可視性修飾子public / internal / protected / private
  • 特殊クラス
    • data class: データ保持用
    • enum class: 列挙型
    • object: シングルトン
    • companion object: 静的メンバー代替

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?