class Father{
public Father(int i){
System.out.println("父类构造方法 -- Father(int i)");
}
}
public class Child_Constrctor extends Father{
public Child_Constrctor(int i ,String s) {
//super(i);
System.out.println("子类构造方法 -- Child_Constrctor(String s ,int i) -- )");
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
在这段代码中,public Child_Constrctor(int i ,String s)这行编译器会报错:
Implicit super constructor Father() is undefined. Must explicitly invoke another constructor
因为在父类中已经自定义了一个带参数的构造方法,那么编译器将不会给父类添加默认的无参构造方法Father(),所以此时系统无法找到父类默认无参构造方法Father()
俩种修改方法:
1.在子类构造方法中添加super(i);显示的调用父类构造方法。
2.在父类中显示的声明无参构造方法:
public Father(){
System.out.println("父类构造方法 -- Father()");
}
方法一修改后的代码:
class Father{
public Father(int i){
System.out.println("父类构造方法 -- Father(int i)");
}
}
public class Child_Constrctor extends Father{
public Child_Constrctor(int i ,String s) {
super(i);//调用父类不同的构造方法
System.out.println("子类构造方法 -- Child_Constrctor(String s ,int i) -- )");
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Child_Constrctor C = new Child_Constrctor(1,"99");
}
}
打出来的log:
父类构造方法 -- Father(int i)
子类构造方法 -- Child_Constrctor(String s ,int i) -- )
方法二修改后的代码:
class Father{
public Father(int i){
System.out.println("父类构造方法 -- Father(int i)");
}
public Father(){
System.out.println("父类构造方法 -- Father()");
}
}
public class Child_Constrctor extends Father{
public Child_Constrctor(int i ,String s) {
super(); //调用父类不同的构造方法
System.out.println("子类构造方法 -- Child_Constrctor(String s ,int i) -- )");
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Child_Constrctor C = new Child_Constrctor(1,"99");
}
}
打印出来的log为:
父类构造方法 -- Father()
子类构造方法 -- Child_Constrctor(String s ,int i) -- )