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のコンストラクタとは?

Posted at

ンストラクタとは、クラスからオブジェクトを生成する際に呼び出される特殊なメソッドのことです。主にオブジェクトの初期化処理に使われます。

特徴

特徴 内容
メソッド名とクラス名が同じ class Sample の場合、コンストラクタも Sample()
戻り値を持たない void などは書かず、戻り値そのものが存在しない
new演算子で呼ばれる new クラス名() により自動的に実行される
複数定義できる 引数の数や型が異なれば、オーバーロード可能

基本的な使用例

public class Sample {
    int num;

    // コンストラクタ
    public Sample(int n) {
        num = n;
        System.out.println("コンストラクタが呼び出されました。num = " + num);
    }

    public static void main(String[] args) {
        Sample s = new Sample(10);  // コンストラクタが自動的に呼ばれる
    }
}

実行結果:
コンストラクタが呼び出されました。num = 10

コンストラクタのオーバーロード(重載)

public class Person {
    String name;
    int age;

    // 引数なしコンストラクタ
    public Person() {
        this.name = "未設定";
        this.age = 0;
    }

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

このように、同じクラスに複数のコンストラクタを定義することで、用途に応じた柔軟なオブジェクト生成が可能になります。

コンストラクタと this の関係

thisキーワードを使うことで、フィールドと引数の変数名が同じときの区別が可能です。

public class Book {
    String title;

    public Book(String title) {
        this.title = title; // フィールドtitleに引数titleを代入
    }
}

まとめ

ポイント 内容
コンストラクタは初期化処理に使う クラスのインスタンスを生成する際に自動的に呼ばれる
戻り値なし 戻り値の型を書く必要はない(voidも不要)
オーバーロード可 複数の初期化パターンに対応可能
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?