java继承当中都有一些什么样的构造函数规则?

6.继承当中的构造函数规则  

继承当中的构造函数规则貌似复杂: 记住我给你的以下几条口诀, 你高枕无忧。1)如果你在某类中写了带参构造函数,系统就不会再为你在那类中自动添加无参构造函数了。2)如你没有写无参构造函数,且机器也不会为你自动添加这个无参构造函 数时(因为你已经有带参构造函数了),你不可以主动调无参构造函数。3)子类的构造函数中不能人为的写两个super。4)构造函数中要是你人工想写super,super必须为第一句话。构造函数中要是你不写super,机器会为你加无参数super().5)既然super必须为第一句话,创建子类对象时,构造函数调用次序为,先最低的超类直到最高的子类。

例1.6.1---

class AAAMark_to_win {
    AAAMark_to_win() {
        System.out.println("Inside AAAMark_to_win's constructor.");
    }
    AAAMark_to_win(int j) {
        System.out.println(j);
    }
}
class BBB extends AAAMark_to_win {
    BBB() {
        super(3);
        System.out.println("Inside BBB's constructor.");
    }
    BBB(int i) {
        System.out.println(i);
    }
}
class C extends BBB {
    C(int a) {
/*super必须是第一句话,彻底不写也行。因为机器会为你自动加。
super must be the first statement. without it, also ok.the result
is exactly the same as right now, because machine will add automatically for you. but if you have it, it must be the first statement.
*/      
//        super();//注意这上下两句,只能保留一个
        super(1);
        System.out.println("Inside C's constructor.");
    }
}

public class Test {
    public static void main(String args[]) {
/*这里你不能写成C(),即使不谈继承,也一样。因为你已经有C(int a) {} ,系统不会为你自动添加C() {} 。
 
here you can not write as new C(); even without inheritance,still, you can not write as new C(); because if you have C(int a) {} already, machine will not automatically add C() {} for you.*/
        C c = new C(5);
    }
}

更多请见:http://www.mark-to-win.com/tutorial/java_3_InheritanceConstrutor.html

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值