Java默认构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4488716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java default constructor
提问by antanis
What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
究竟什么是默认构造函数——你能告诉我以下哪一个是默认构造函数,它与任何其他构造函数的区别是什么?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
采纳答案by OrangeDog
Neither of them. If you define it, it's not the default.
他们都不是。如果您定义它,则它不是默认值。
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String
, int
and int
, and that the class itself is public:
默认构造函数是自动生成的无参数构造函数,除非您定义另一个构造函数。任何未初始化的字段都将设置为其默认值。对于您的示例,假设类型为String
, int
andint
并且类本身是公共的,它看起来像这样:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This is exactly the same as
这与
public Module()
{}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
和完全没有构造函数完全一样。但是,如果您至少定义了一个构造函数,则不会生成默认构造函数。
Reference: Java Language Specification
参考:Java 语言规范
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
如果一个类不包含构造函数声明,则隐式声明一个没有形式参数和 throws 子句的默认构造函数。
Clarification
澄清
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
从技术上讲,默认初始化字段的不是构造函数(默认或其他)。但是,我将其作为答案,因为
- the question got the defaults wrong, and
- the constructor has exactly the same effect whether they are included or not.
- 这个问题的默认值是错误的,并且
- 无论是否包含它们,构造函数都具有完全相同的效果。
回答by Jim
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
如果您没有在类中定义任何构造函数,则会创建默认构造函数。它只是一个无参数构造函数,什么都不做。编辑:除了调用 super()
public Module(){
}
回答by OrangeDog
A default constructor does not take any arguments:
默认构造函数不接受任何参数:
public class Student {
// default constructor
public Student() {
}
}
回答by kem
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
如果您没有在类中明确定义至少一个构造函数,则编译器会自动生成一个默认构造函数。您已经定义了两个,因此您的类没有默认构造函数。
Per The Java Language Specification Third Edition:
根据Java 语言规范第三版:
8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided...
8.8.9 默认构造函数
如果一个类不包含构造函数声明,则自动提供一个不带参数的默认构造函数......
回答by sunil
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
当没有提供显式构造函数时,Java 提供了一个默认构造函数,它不接受任何参数,也不执行任何特殊操作或初始化。
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
隐式默认构造函数采取的唯一操作是使用 super() 调用来调用超类构造函数。构造函数参数为您提供了一种为对象的初始化提供参数的方法。
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
下面是一个包含 2 个构造函数的多维数据集类的示例。(一个默认构造函数和一个参数化构造函数)。
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
回答by Aniket Thakur
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
一般术语是,如果您没有在对象中提供任何构造函数,则会自动放置无参数构造函数,称为默认构造函数。
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
如果您确实定义了一个与不提供任何参数的构造函数相同的构造函数,则它通常被称为无参数构造函数。这只是一种约定,尽管有些程序员更喜欢将此显式定义的无参数构造函数称为默认构造函数。但是,如果我们通过命名来明确定义一个,那么它不会使其成为默认值。
As per the docs
根据文档
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
如果一个类不包含构造函数声明,则隐式声明一个没有形式参数和 throws 子句的默认构造函数。
Example
例子
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
将自动修改(通过添加默认构造函数)如下
public class Dog{
public Dog() {
}
}
and when you create it's object
当你创建它的对象时
Dog myDog = new Dog();
this default constructor is invoked.
调用此默认构造函数。
回答by Koushik85
Hi. As per my knowledge let me clear the concept of default constructor:
你好。据我所知,让我清除默认构造函数的概念:
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
编译器自动为任何没有构造函数的类提供一个无参数的默认构造函数。此默认构造函数将调用超类的无参数构造函数。在这种情况下,如果超类没有无参数构造函数,编译器会报错,因此您必须验证它是否有。如果你的类没有显式超类,那么它有一个隐式的 Object 超类,它有一个无参数的构造函数。
I read this information from the Java Tutorials.
我从Java 教程中阅读了此信息。
回答by user1923551
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
如果一个类没有程序员提供的任何构造函数,那么java编译器将添加一个带有out参数的默认构造函数,该构造函数将通过super()调用在内部调用超类构造函数。这称为默认构造函数。
In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.
在您的情况下,当您以编程方式添加它们时,没有默认构造函数。如果您没有添加构造函数,则编译器生成的默认构造函数将如下所示。
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
注意:在侧默认构造函数中,它也会添加 super() 调用,以调用超类构造函数。
Purpose of adding default constructor:
添加默认构造函数的目的:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
构造函数的职责是初始化实例变量,如果没有实例变量,您可以选择从类中删除构造函数。但是当您继承某个类时,您的类有责任调用超类构造函数以确保超类正确初始化其所有实例变量。
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
这就是为什么如果没有构造函数,java编译器会添加一个默认构造函数并调用超类构造函数。
回答by uttsav
When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.
当我们没有为类显式定义构造函数时,java 会为该类创建一个默认构造函数。它本质上是一个非参数化的构造函数,即它不接受任何参数。
The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.
默认构造函数的工作是调用超类构造函数并初始化所有实例变量。如果超类构造函数不存在,那么它会自动将实例变量初始化为零。因此,这服务于使用构造函数的目的,即初始化对象的内部状态,以便创建实例的代码将具有完全初始化的可用对象。
Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.
一旦我们为类定义了自己的构造函数,就不再使用默认的构造函数。因此,它们实际上都不是默认构造函数。
回答by Yergalem
default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.
默认构造函数是指在没有任何程序员定义的构造函数的情况下由编译器自动生成的构造函数。
If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super()
, has no throws clause as well no formal parameters.
如果程序员没有提供构造函数,编译器会隐式声明一个调用的默认构造函数super()
,没有 throws 子句,也没有形式参数。
E.g.
例如
class Klass {
// Default Constructor gets generated
}
new Klass(); // Correct
-------------------------------------
class KlassParameterized {
KlassParameterized ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassParameterized(); //// Wrong - you need to explicitly provide no-arg constructor. The compiler now never declares default one.
--------------------------------
class KlassCorrected {
KlassCorrected (){ // No-arg Constructor
/// Safe to Invoke
}
KlassCorrected ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassCorrected(); /// RIGHT -- you can instantiate