Java|Java "There is no default constructor available in.."问题
Java Tutorial: Extending a Class that has Explicit Constructors
In the following code, why it doesn't compile, but does when B() is defined?
class B {
int x;
//B () {x=300;
}
B (int n) {x=n;
}
int returnMe () {return x;
}
}class C extends B {
}public class Inh3 {
public static void main(String[] args) {
}
}
(answer below.)
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
Solution
the answer to the constructor mystery is that, if one provides any constructor, one must define all constructors.
「如果一个人提供了任意一个构造器,他就应该定义所有的构造器。」
Peter Molettiere on Apple's Java forum gave excellent answers:
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is** not included.** If you define any constructor, then you must define all constructors.
如果你写了一个构造器,那默认构造器就不会自动生成了。所以子类默认构造器在调用父类默认构造器的时候会找不到。
When you try to instantiate C, it has to call super() in order to initialize its super class. You don't have a super(), you only have a super(int n), so C can not be defined with the default constructor C() { super(); }. Either define a no-arg constructor in B, or call super(n) as the first statement in your constructors in C.
So, the following would work:
class B {
int x;
B() { } // a constructor
B( int n ) { x = n;
} // a constructor
int returnMe() { return x;
}
}class C extends B {
}
or this:
class B {
int x;
B( int n ) { x = n;
} // a constructor
int returnMe() { return x;
}
}class C extends B {
C () { super(0);
} // a constructor
C (int n) { super(n);
} // a constructor
}
【Java|Java "There is no default constructor available in.."问题】If you want to make sure that x is set in the constructor, then the second solution is preferable.
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 事件代理
- Java|Java OpenCV图像处理之SIFT角点检测详解
- java中如何实现重建二叉树
- 数组常用方法一
- 【Hadoop踩雷】Mac下安装Hadoop3以及Java版本问题
- Java|Java基础——数组
- RxJava|RxJava 在Android项目中的使用(一)
- java之static、static|java之static、static final、final的区别与应用
- Java基础-高级特性-枚举实现状态机