LoginSignup
7
2

More than 5 years have passed since last update.

エラー『Implicit super constructor Class() is undefined. Must explicitly invoke another constructor』回避方法

Posted at

1. 発生条件

例えば以下のようにクラスAを定義し、Aの子クラスとしてBを定義する。


class A {
}

class B extends A{
    public B(int b) {
    }
}

このままではエラーは発生しないが、以下のようにクラスAのコンストラクタを明示的に定義したとき、


class A {
    public A(int a) {
    }
}

class B extends A{
    public B(int b) {
    }
}

Implicit super constructor  A() is undefined. Must explicitly invoke another constructor

というようなエラーが発生する。
これは、クラスBのコンストラクタが親クラスAのデフォルトコンストラクタであるpublic A()を参照しようとしているが、定義されていないためである。

2. 回避方法

回避方法としては2通りある。

2-1. デフォルトコンストラクタを明示的に定義

以下のように、public A()を明示的に定義すればエラーを回避できる。


class A {
    public A() {
    }

    public A(int a) {
    }
}

2-2. super()を明示的に呼び出す

以下のように、Aで定義してあるコンストラクタの引数に合わせたsuper()を呼び出せばエラーを回避できる。

class A {
    public A(int a) {
    }
}

class B extends A{
    public B(int b) {
        super(b);
    }
}

7
2
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
7
2