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?

Javaのコンストラクタについて

Last updated at Posted at 2025-05-23

コンストラクタ

  • インスタンスを生成するときに呼ばれる処理。

前書き:インスタンスとは

  • 後述nコードブロックにおいて、クラス定義から、Person taro = new Person("太郎", 20);などと実際につくられたものがインスタンスである。

コンストラクタとは

  • インスタンスを作成したタイミングで設定の読み込みや、フィールドの初期化等の処理をしたい場合に宣言を行う。
  • 下記のコンストラクタは、インスタンスを作ったときに自動的に呼ばれて、
    1. 名前(name)と年齢(age)を引数として受け取る
    2. その値を、this.name = name; のように、Personの中の this.name, this.age にセットする
      • this.name : クラスが持っている変数(フィールド)
      • name : 引数(コンストラクタに渡された値)
// クラス定義
public class Person {
    String name;
    int age;

    // コンストラクタ
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

コンストラクタの書き方

  • メソッド名の部分はクラス名と同じ
  • 戻り値の宣言が存在しない

新しいインスタンスの生成

Person taro = new Person("太郎", 20);
  • Person クラスの設計図をもとに 新しいオブジェクト(インスタンス)を作る
  • new によって自動的に Person(String name, int age) が呼ばれる
    • Javaの仕様では、new クラス名(...)(...) の中身を見て、対応するコンストラクタを探して呼び出す。
  • "太郎" と 20 が引数として渡される
  • this.name = "太郎";, this.age = 20; のように、値をセットする。
    • this.name: この場合では、Personクラスが持っている nameという変数
  • taro という変数に、そのオブジェクトの住所(参照)が代入される
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?