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 1 year has passed since last update.

Java_引数ありのコンストラクタ

Posted at

paizaラーニングforTEAM Java入門編
レッスン8の#03

8-#03
// 引数ありのコンストラクタ

// コンストラクタはnewというキーワードを使い、オブジェクトを作るときに呼び出される
// コンストラクタはメソッドではない
// コンストラクタにはクラスと同じ名前をつける

public class Main {
    public static void main(String[] args) {
        Box box = new Box("鋼鉄の剣"); // Boxオブジェクトを作るときに宝箱の中身を指定
        box.open();

        System.out.println(); // 空の行を出力

        JewelryBox jewelryBox = new JewelryBox("魔法の指輪");
        jewelryBox.look();
        jewelryBox.open();
    }
}

class Box {
    public String myItem;
    
    // Boxオブジェクトを作るときに宝箱の中身を指定できるようにする
    // そのためにコンストラクタに引数を指定する
    public Box(String item) {
        myItem = item; // コンストラクタの引数をメンバー変数に代入_メンバー変数の初期化という
    }

    public void open() {
        System.out.println("宝箱を開いた。" + myItem + "を手にいれた。");
    }
}

class JewelryBox extends Box {
    // コンストラクタはメソッドと違って親クラスから引き継がれない
    // 子クラスで引数のあるコンストラクタを使う場合は子クラスでも引数のあるコンストラクタを記述する必要がある
    // 子クラスのコンストラクタで親クラスの、引数のあるコンストラクタを呼び出す必要がある
    public JewelryBox(String item) {
        super(item); // super(item)で親クラスのitemを引数にもつコンストラクタを呼び出す_super()はコンストラクタの1行目に書かなければいけない
    }
    
    public void look() {
        System.out.println("宝箱はキラキラと輝いている。");
    }
}
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?