构造方法 -- super()方法

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) -- )



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值