如果父类具有参数构造函数,为什么在父类中需要默认构造函数? [英] Why default constructor is required in a parent class if it has an argument-ed constructor?

查看:143
本文介绍了如果父类具有参数构造函数,为什么在父类中需要默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在父类中需要(显式)默认构造函数,如果它有一个有争议的构造函数

Why default constructor is required(explicitly) in a parent class if it has an argumented constructor

class A {    
  A(int i){    
  }
}

class B extends A {
}

class Main {    
  public static void main(String a[]){
    B b_obj = new B();
  }
}

这将是一个错误。

推荐答案

这里有两个方面:


  • 如果您执行明确指定构造函数(如在 A 中),Java编译器将创建无参数你的构造函数。

  • If you do specify a constructor explicitly (as in A) the Java compiler will not create a parameterless constructor for you.

如果没有明确指定构造函数(如在 B 中) Java编译器将为您创建一个无参数构造函数:

If you don't specify a constructor explicitly (as in B) the Java compiler will create a parameterless constructor for you like this:

B()
{
    super();
}


(可访问性取决于关于类本身的可访问性。)

(The accessibility depends on the accessibility of the class itself.)

这是试图调用超类无参数构造函数 - 所以它必须存在。您有两种选择:

That's trying to call the superclass parameterless constructor - so it has to exist. You have two options:


  • A
  • B 中显式提供无参数构造函数,它使用适当的 int 参数。

  • Provide a parameterless constructor explicitly in A
  • Provide a parameterless constructor explicitly in B which explicitly calls the base class constructor with an appropriate int argument.

这篇关于如果父类具有参数构造函数,为什么在父类中需要默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆