故事从这个报错开始:
There is no default constructor available in 'Hero'
这是我的错误代码:
class Hero{
public String name;
public String useWeapons;
public Hero(String name, String useWeapons){
this.name = name;
this.useWeapons = useWeapons;
}
}
class skills extends Hero{
String Q;
String E;
String passive;
public skills(String name, String useWeapons, String E, String Q, String passive) {
this.name = name;
this.useWeapons = useWeapons;
this.E = E;
this.Q = Q;
this.passive = passive;
}
}
我一开始很疑惑,为什么会报错,因为我觉得我跟下面的代码没有区别:
class Person{
String name;
double height;
public void rest(){
System.out.println("人类需要休息!");
}
}
class student extends Person{
String major;
public void study(){
System.out.println("major:" + major);
}
public student(String name, double height, String major){
//直接继承父类的属性并构造对象;
this.name = name;
this.height = height;
//构造自己的属性
this.major = major;
}
}
以上代码来自JAVA程序设计实战
于是我找到了以下文章:关于java构造函数 的错误 there is no default constructor available in …
我的代码加上super()后:
class Hero{
public String name;
public String useWeapons;
public Hero(String name, String useWeapons){
this.name = name;
this.useWeapons = useWeapons;
}
}
class skills extends Hero{
String Q;
String E;
String passive;
public skills(String name, String useWeapons, String E, String Q, String passive) {
super(name, useWeapons);//这里加上super()从而调用父类的构造函数;
this.E = E;
this.Q = Q;
this.passive = passive;
}
}
继承了父类,那就是父类的延伸,要实例化的时候自然是父类先实例化
所以我们只要在子类的构造方法中显示的调用父类的有参构造 super(args)即可。
关于super:关于Java中super的应用中写的很详细。
super( ) ( 这种形式指的是:调用父类没有参数的构造方法(也叫构造函数)注意: 这里super( ) 只能放在子类的构造方法里面,并且只能放在构造方法的首句)
以我浅薄的知识来理解,下面的写法当然没问题,但是如果不在父类写构造函数,那么要建父类的对象是 建不了的。
class Hero{
public String name;
public String useWeapons;
}
class skills extends Hero{
String Q;
String E;
String passive;
public skills(String name, String useWeapons, String E, String Q, String passive) {
//直接调用,不在父类弄构造函数
this.name = name;
this.useWeapons = useWeapons;
this.E = E;
this.Q = Q;
this.passive = passive;
}
}