super调用基类构造方法

本文深入解析了Java子类构造方法中使用super语句调用基类构造函数的机制及其必要性,强调了super语句必须位于子类构造方法的第一行的重要性。通过实例代码和分析,阐述了正确使用super语句对于维护类层次结构和代码可读性的关键作用。

源代码:


class Grandparent {

  public Grandparent() {
    System.out.println("GrandParent Created.");
}

  public Grandparent(String string) {
    System.out.println("GrandParent Created.String:" + string);
}
}

class Parent extends Grandparent {

  public Parent() {
    //super("Hello.Grandparent.");
  System.out.println("Parent Created");
    //super("Hello.Grandparent.");
}
}

class Child extends Parent {

 public Child() {
   System.out.println("Child Created");
}
}

public class ZXC {

  public static void main(String args[]) {
     Child c = new Child();
}
}

super语句放在第一句时结果为:

super语句放在第二句时结果为:

结论:通过super语句调用基类构造函数,必须放在子类构造方法中的第一句。

 

转载于:https://www.cnblogs.com/96ZYJ/p/4946253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值