LoginSignup
0
0

Java silver向け 例題 継承 コンストラクタ

Last updated at Posted at 2024-04-09

次のコードはコンパイルエラーになりますか?

class sampleSuper {
	sampleSuper(int a) {
	}
}

class sampleSub extends sampleSuper{
	sampleSub(int i){
	}
}

答え














サブクラスのコンストラクタ
sampleSub(int i){}でコンパイルエラーになる。

サブクラスのコンストラクタの引数の有無に関わらず、コンストラクタの1番目に暗黙的にsuper();が追加される。

class sampleSub extends sampleSuper{
	sampleSub(int i){
	//super();
     }
}

スーパークラスのコンストラクターsampleSuper(){}が呼び出されるが、スーパークラスのコンストラクタに引数が合致するものがないためコンパイルエラーになる。

スーパークラスにコンストラクタが一つもない場合は暗黙的にsampleSuper(){}が追加される。(その場合コンパイルエラーが解決される)

class sampleSuper {
	//sampleSuper(){}
}

スーパークラスにコンストラクタが明記的に記述される場合は暗黙的にsampleSuper(){}が追加されない(問題文)。

下記のようにサブクラスのコンストラクタに引数ありのスーパークラスのコンストラクタを明記すると、暗黙的に引数なしのコンストラクタは追加されない。(その場合もコンパイルエラーが解決される)

class sampleSuper {
	sampleSuper(int a) {
	}
}

class sampleSub extends sampleSuper{
	sampleSub(int i){
    	super(100);
     }
}

コンストラクタの呼び出しはコンストラクタの1番上に書かなければいけない。
例えばサブクラスのコンストラクタでsuper()とthis()を併用するとsuper()が2回呼び出されることになるためコンパイルエラーになる。

class sampleSuper {
    //sampleSuper(){}
}
class sampleSub extends sampleSuper{
    sampleSub(){
        //super();
    }
	sampleSub(int i){
    	super();
         this();
     }
}
0
0
1

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