次のコードはコンパイルエラーになりますか?
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();
}
}