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?

More than 5 years have passed since last update.

Kotlinで簡単なオブジェクトを作成する

Posted at

はじめに

Kotlin でクラスを扱うときのための基本的なことのメモ

 簡単なクラスの定義

ここでは簡単なクラスの定義をまとめます。以下には車を例に簡単なクラスの定義などを簡単にまとめます。引数としてメーカーを表すtypeと作られた年代を示すmodelを用意します。


class Car(var type:String,var model:Int){

    init{
        println("this class is initialized")
    }
}

ここで、initはクラスが初期化されたときに自動的に一番最初に実行されます。
例えば、以下のコードを実行します。


class Car(var type:String,var model:Int){

    init{
        println("this class is initialized")
    }
}

fun main(){
    var car = Car("Toyota",1999)
}

実行結果として以下の結果が得られます。


this class is initialized

プロパティへのアクセス

上のコードで初期化したオブジェクトのプロパティへアクセスするには、以下のようにしてアクセスします。

car.kt

class Car(var type:String,var model:Int){

    init{
        println("this class is initialized")
    }
}

fun main(){
    var car = Car("Toyota",1999)
    println(car.type)
    println(car.model)
}

実行結果として以下の結果が得られます。


this class is initialized
Toyota
1999

メソッドの作成

メソッドの作成は以下のようにして行います。このコードでは、車が作られてから何年たったかを計算して値を返しています。


class Car(var type:String,var model:Int){
    init {
        println("this class is initialized")
    }

    fun getYearOfCar():Int{
        return 2019-model
    }
}

リストによる複数のオブジェクトの作成

複数のオブジェクトを作成するとき、リストを使ってオブジェクトを作成することができます。


class Car(var type:String,var model:Int){
    init {
        println("this class is initialized")
    }

    fun getYearOfCar():Int{
        return 2019-model
    }
}

fun main(){
    //リスト
    var listOfCar = arrayListOf<Car>()
    listOfCar.add(Car("toyota",1999))
    listOfCar.add(Car("matsuda",2010))
    for (car in listOfCar){
        println(car.type)
        println(car.model)
    }
}

実行結果


this class is initialized
this class is initialized
toyota
1999
matsuda
2010
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?