java构造方法继承_Java构造器继承

因为构建子类对象的方式可能与构建超类的方式不同。您可能不希望子类的客户端能够调用超类中可用的某些构造函数。

一个愚蠢的例子:class Super {

protected final Number value;

public Super(Number value){

this.value = value;

}}class Sub {

public Sub(){ super(Integer.valueOf(0)); }

void doSomeStuff(){

// We know this.value is an Integer, so it's safe to cast.

doSomethingWithAnInteger((Integer)this.value);

}}// Client code:Sub s = new Sub(Long.valueOf(666L)):

// Devilish invocation of Super constructor!s.doSomeStuff();

// throws ClassCastException

或者更简单:class Super {

private final String msg;

Super(String msg){

if (msg == null) throw new NullPointerException();

this.msg = msg;

}}class Sub {

private final String detail;

Sub(String msg, String detail){

super(msg);

if (detail == null) throw new NullPointerException();

this.detail = detail;

}

void print(){

// detail is never null, so this method won't fail

System.out.println(detail.concat(": ").concat(msg));

}}// Client code:Sub s = new Sub("message");

// Calling Super constructor - detail is never initialized!s.print();

// throws NullPointerException

从本例中可以看出,您需要某种方式声明“我想继承这些构造函数”或“我想继承除这些构造函数之外的所有构造函数”,然后还必须指定默认构造函数继承首选项,以防有人在超类中添加新构造函数.或者,如果您想要“继承”它们,那么只需要从超类中重复构造函数,这可以说是更明显的方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值