LoginSignup
2
0

More than 1 year has passed since last update.

【メモ】Kotlinのクラスと継承

Last updated at Posted at 2022-04-12

はじめに

改めて継承などについて学んだので、かなりコンパクトにまとめました。
※間違っている部分があれば指摘していただけますと幸いです。

用語の概要

  • クラス階層
    • クラスが親と子の階層構造で構成されている配置のこと
    • 階層図は通常親が子の上に表示するように描かれる
  • 子・サブクラス
    • 階層構造で他のクラスの下にある全てのクラス
  • 親・スーパークラス・基底クラス
    • 1つ以上の子クラスを持つ全てのクラス
  • ルート・トップレベルクラス
    • クラス階層の最上位(またはルート)にあるクラス
  • 継承
    • 子クラスが親クラスの全てのプロパティとメソッドを含む(継承する)ことを意味する
    • これによりコードの共有や再利用が可能になる

抽象クラスとは?

  • 完全に実装されていないため、インスタンス化出来ないクラスのこと
  • スケッチのようなもの
    • スケッチ(抽象クラス)を使用して、実際のオブジェクトインスタンスをビルドするための設計図(クラス)を作成する
  • 宣言はabstractで始める
  • 抽象クラス・関数にopenアノテーションを付ける必要は無い
abstract class Polygon {
   abstract fun draw()
}

class Rectangle : Polygon() {
   override fun draw() {
       // draw the rectangle
   }
}
  • 抽象化されていないopenメンバを、抽象化されたメンバでオーバーライド出来る
open class Polygon {
    open fun draw() {
        // some default polygon drawing method
    }
}

abstract class WildShape : Polygon() {
    // Classes that inherit WildShape need to provide their own
    // draw method instead of using the default on Polygon
    abstract override fun draw()
}

継承について

  • 継承できるのはabstractか、openキーワードでマークされたもののみ
    • ※Kotlinのクラス・メソッドはデフォルトでfinal
  • メソッドや属性をオーバーライドするには、override修飾子が必要
open class Dog {                
    open fun sayHello() {       
        println("wow wow!")
    }
}

class Yorkshire : Dog() {       
    override fun sayHello() {   
        println("wif wif!")
    }
}

fun main() {
    val dog: Dog = Yorkshire()
    dog.sayHello() // wif wif!
}
  • 親で定義されている関数を呼び出すときはsuperキーワードを使用
abstract class Dwelling {
    
    abstract fun floorArea(): Double
}

open class RoundHut(val radius: Double) : Dwelling() {
    
    override fun floorArea(): Double {
        return 3.14 * radius * radius
    }
}

class RoundTower(
    radius: Double,
    val floors: Int
) : RoundHut(radius) {
    
    override fun floorArea(): Double {
        return super.floorArea() * floors
    }
}

fun main() {
    val roundHut = RoundHut(5.0)
    println(roundHut.floorArea()) // 3.14 * 5 * 5
    
    val roundTower = RoundTower(5.0, 3)
    println(roundTower.floorArea()) // 3.14 * 5 * 5 * 3
}

/**
* 出力結果
*
* 78.5
* 235.5
*/

参考資料

おわりに

ここまで読んでいただき、ありがとうございました。
何かありましたらコメントをお願いします。

2
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
2
0