简体   繁体   English

以下哪个类具有默认构造函数?

[英]Which of these classes has a default constructor?

Which of these classes has a default constructor? 以下哪个类具有默认构造函数? I'm thinking just A but am I wrong? 我只想A,但是我错了吗?

class A {}
class B {B() {}}
class C {C(int j) {}}

You are correct. 你是对的。 A default constructor is, by definition, created when no constructor is defined. 根据定义,当未定义构造函数时,将创建默认构造函数。 Since A does not have a constructor defined it will have a default constructor created for it. 由于A没有定义构造函数,它将为它创建一个默认构造函数。

Technically speaking, you could say B has a default constructor since a parameter-less constructor is what would be created if none is defined. 从技术上讲,您可以说B有一个默认的构造函数,因为如果没有定义任何参数,就会创建一个无参数的构造函数。

Reference: http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9 参考: http : //docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9

Precisely. 精确地

Class A has a default constructor because you're not providing any constructor for the class. A有一个默认的构造函数,因为你没有提供的类中的任何构造。 The compiler, therefore, automatically provides a no-argument, default constructor. 因此,编译器会自动提供一个无参数的默认构造函数。 This default constructor will call the no-argument constructor of the superclass (in this case the Object class). 此默认构造函数将调用超类的无参数构造函数(在本例中为Object类)。 The second class, Class B , is providing a no-argument constructor, but it is not default as the compiler is not providing it for you. 第二个类B类提供了无参数的构造函数,但是它不是默认值,因为编译器没有为您提供它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM