LoginSignup
8
6

More than 5 years have passed since last update.

コンストラクタでの暗黙的super()呼び出し

Posted at

Javaではサブクラスのコンストラクタで明示的にスーパークラスのコンストラクタ呼び出しを行わない場合についても暗黙的に呼び出しを行う。

public class Sample {
    public static void main(String args[]) {
        Child obj1 = new Child();
    }
}

class Parent {
    Parent() {
        System.out.println("parent");
    }
}

class Child extends Parent {
    Child() {
        // super();
        System.out.println("child");
    }
}
# 実行結果
parent
child

引数ありのコンストラクタを呼び出した場合についても、引数なしのスーパークラスのコンストラクタが呼び出される。

public class Sample {
    public static void main(String args[]) {
        Child obj2 = new Child("test");
    }
}

class Parent {
    Parent() {
        System.out.println("parent");
    }
}

class Child extends Parent {
    Child(String value) {
        System.out.println("child");
    }
}
# 実行結果
parent
child

スーパークラスにも引数ありのコンストラクタを定義した場合も、引数なしのコンストラクタが呼び出される。

public class Sample {
    public static void main(String args[]) {
        Child obj2 = new Child("test");
    }
}

class Parent {
    Parent() {
        System.out.println("parent(引数なし)");
    }

    Parent(String value) {
        System.out.println("parent(引数あり)");
    }
}

class Child extends Parent {
    Child(String value) {
        System.out.println("child");
    }
}
# 実行結果
parent(引数なし)
child

なので、明示的に引数ありのコンストラクタを呼び出す必要がある。

public class Sample {
    public static void main(String args[]) {
        Child obj2 = new Child("test");
    }
}

class Parent {
    Parent() {
        System.out.println("parent(引数なし)");
    }

    Parent(String value) {
        System.out.println("parent(引数あり)");
    }
}

class Child extends Parent {
    Child(String value) {
        super(value);
        System.out.println("child");
    }
}
# 実行結果
parent(引数あり)
child
8
6
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
8
6