java中父类与子类构造函数的执行顺序

每次当用new关键字创建出一个子类对象时,那么程序会先执行父类中不带参数的构造函数,然后再执行子类的构造函数.

eg:   我建了三个类,一个是父类(A_constructor) , 第二个是子类(B_constructor) , 第三个是测试用的类(Test_constructor) . 代码及运行结果如下

父类:

public class A_constructor {

 public A_constructor(){
  System.out.println("父类的无参数的构造函数A_constructor()");
 }
 public A_constructor(int n){
  System.out.println("父类带参数的构造函数A_constructor(n) : "+n);
 }
}

子类:

public class B_constructor extends A_constructor{
 public B_constructor(){
  System.out.println("子类的无参数构造函数B_constructor()");
 }
 public B_constructor(int n){
  System.out.println("子类带参数的构造函数B_constructor(n): "+n);
 } }

测试类:

public class Test_constructor {

 public static void main(String args[]){
  B_constructor one = new B_constructor();  //不带参数
  B_constructor two = new B_constructor(2);  //带了参数
  System.out.println("测试结束");
 }
}


运行结果:

父类的无参数的构造函数A_constructor()
子类的无参数构造函数B_constructor()
父类的无参数的构造函数A_constructor()
子类带参数的构造函数B_constructor(n): 2
测试结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值