我真的需要在java中定义默认构造函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3641114/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:03:51  来源:igfitidea点击:

Do I really need to define default constructor in java?

javaconstructordefault-constructor

提问by Ayush Goyal

It works fine when constructors are not defined, but gives errors if I define a parameterized constructor and not a default one and not passing any values while creating an object. I thought constructors are predefined.

当未定义构造函数时它工作正常,但如果我定义参数化构造函数而不是默认构造函数并且在创建对象时不传递任何值,则会出现错误。我认为构造函数是预定义的。

Why do I need to define a default constructor if I've defined a parameterized constructor? Ain't default constructor predefined?

如果我定义了参数化构造函数,为什么还需要定义默认构造函数?默认构造函数不是预定义的吗?

采纳答案by Justin Ardini

A default (no-argument) constructor is automatically created onlywhen you do not define any constructor yourself.

当您自己未定义任何构造函数时,才会自动创建默认(无参数)构造函数。

If you need two constructors, one with arguments and one without, you need to manually define both.

如果您需要两个构造函数,一个带参数,一个不带参数,则需要手动定义两者。

回答by Noon Silk

A no-arg constructor is automatically inserted for you, if you don't write one. This means, if you write a constructor with some parameters, it will be the only constructor you have, so you must pass some values for those parameters to create an instance of it.

如果您不编写,则会自动为您插入一个无参数构造函数。这意味着,如果您编写带有一些参数的构造函数,它将是您拥有的唯一构造函数,因此您必须为这些参数传递一些值以创建它的实例。

回答by daphshez

This is exactly the expected behavior.

这正是预期的行为。

Java automatically generates a default (no arguments constructors) for classes that don't have any constructor.

Java 自动为没有任何构造函数的类生成默认值(无参数构造函数)。

If you define another constructor (with arguments), default constructor will not be generated. If you still want one, you need to define it yourself.

如果您定义另一个构造函数(带参数),则不会生成默认构造函数。如果你仍然想要一个,你需要自己定义它。

回答by Sahil J

While all the answers above are correct, it's a bit difficult for new-comers to wrap it in their head. I will try to answer the question anew for new-comers.

虽然上面的所有答案都是正确的,但对于新人来说,将其包裹在他们的脑海中有点困难。我会尽量为新人重新回答这个问题。

The problem that Ayush was facing was in trying to instantiate an Objectfor a class via a no-arg constructor. This class however has one or more parameterized constructor and this results in a compile time error.

Ayush 面临的问题是试图Object通过无参数构造函数为类实例化 an 。然而,此类具有一个或多个参数化构造函数,这会导致编译时错误。

For example, let us create a class Studentwith a single parameterized constructor and try to instantiate it via the no-arg constructor.

例如,让我们创建一个Student具有单个参数化构造函数的类,并尝试通过无参数构造函数实例化它。

public class Student {

    private String name;
    private int rollNo;

    public Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
    }

    public static void main(String[] args) {
        // The line below will cause a compile error.
        Student s = new Student();
        // Error will be "The constuctor Student() is undefined"
    }
}

Woha! But when we remove the public Student(String name, int rollNo)constructor all-together, the error is gone and the code compiles.

哇!但是当我们一起删除public Student(String name, int rollNo)构造函数时,错误消失并且代码编译。

The reason behind this seeming anomaly lies in the fact that Java only provides us with the default (no-arg) constructor when we do not define any constructor for that class on our own.

这种看似异常的背后的原因在于,当我们自己没有为该类定义任何构造函数时,Java 只为我们提供了默认(无参数)构造函数。

For example, the following class is supplied with a default contructor:

例如,以下类提供了一个默认构造函数:

public class Student {
    private String name;
    private int rollNo;
}

becomes:

变成:

public class Student {

    private String name;
    private int rollNo;

    //Default constructor added by Java.
    public Student() {
        super();
    }
}

In other words, the moment we define any parameterized constructor, we mustalso define a no-arg constructor if we want to instantiate the object of that class via a no-arg constructor.

换句话说,在我们定义任何参数化构造函数的那一刻,如果我们想通过一个无参数构造函数实例化那个类的对象,我们还必须定义一个无参数构造函数。

Also in case of inheritance, a sub-class with no constructors; is supplied one default constructor. This default constructor supplied by Java as above calls the super class's no-arg constructor. If it can't find one, then it will throw an error.

同样在继承的情况下,没有构造函数的子类;提供了一个默认构造函数。Java 提供的这个默认构造函数调用超类的无参数构造函数。如果找不到,则会抛出错误。

So yes it's always a good choice to define a no-arg/default constructor.

所以是的,定义一个无参数/默认构造函数总是一个不错的选择。

Ref : Oracle Java Tutorial

参考:Oracle Java 教程

回答by manisha mulchandani

Whenever you class is complied, if compiler does not find any valid constructor in class (default,parametrized) only then it will substitute auto generated default constructor for your class.

每当您编译类时,如果编译器在类(默认,参数化)中找不到任何有效的构造函数,则它只会为您的类替换自动生成的默认构造函数。

You must have noticed, you can create objects without any default constructor defined in your class, there comes the concept of auto-generated default constructor.As whenever object is created,default constructor is called.

你一定注意到了,你可以在类中没有定义任何默认构造函数的情况下创建对象,有自动生成默认构造函数的概念。因为每当创建对象时,都会调用默认构造函数。

But, If you define Parametrized constructor in your class, that means you restrict the objects to have that parameters

但是,如果您在类中定义参数化构造函数,则意味着您将对象限制为具有该参数

Example:Every employee must have an id.

示例:每个员工都必须有一个 ID。

So,at that time, Compiler will not insert any default constructor there as there is valid constructor in a class.If you need default constructor too, you have to define by yourself.

所以,那时Compiler不会在那里插入任何默认构造函数,因为类中有有效的构造函数。如果你也需要默认构造函数,你必须自己定义。

回答by EnGoPy

There is also one curious case when you must define non argument constructor. As the other wrote, if you don't specify default constructor - Java will do it for you. It's good to understand how "default generated by Java" constructor looks like. In fact it calls constructor of the super class and this is fine. Let's now imagine one case. You are creating Vehicle class:

当您必须定义非参数构造函数时,还有一种奇怪的情况。正如其他人所写,如果您不指定默认构造函数 - Java 将为您完成。了解“由 Java 生成的默认值”构造函数的外观很好。实际上它调用了超类的构造函数,这很好。现在让我们想象一个案例。您正在创建 Vehicle 类:

public class Vehicle {
private String name;
private String engine;

public Vehicle(String name, String engine) {
    this.name = name;
    this.engine = engine;
}

public String makeNoise(){
    return "Noiseee";
} 
}

As we can see Vehicle class has got only one defined 2 arguments constructor. Now let's create Car class which inheritates from Vehicle class:

正如我们所看到的,Vehicle 类只有一个定义了 2 个参数的构造函数。现在让我们创建继承自 Vehicle 类的 Car 类:

public class Car extends Vehicle {

@Override
public String makeNoise() {
    return "Wrrrrrrr....";
}  }

Maybe it looks strange but only one reason why wouldn't it compile is fact that Java cannot create default constructor for Car class which call super Vehicle class. Vehicle class doesn't have no argument constructor and it cannot be generated automatically while 2 arg constructor already exists.

也许它看起来很奇怪,但它不能编译的唯一原因是 Java 无法为调用 super Vehicle 类的 Car 类创建默认构造函数。Vehicle 类没有无参数构造函数,并且当 2 个 arg 构造函数已经存在时它不能自动生成。

I know that it's very rare case, but I found it as a interesting to know.

我知道这是非常罕见的情况,但我发现它很有趣。