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

发布于 2024-09-18 09:32:50 字数 150 浏览 15 评论 0原文

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

惟欲睡 2024-09-25 09:32:51

每当你的类被编译时,如果编译器在类中没有找到任何有效的构造函数(默认,参数化),那么它才会为你的类替换自动生成的默认构造函数。

你一定已经注意到,你可以创建对象如果类中没有定义任何默认构造函数,就会出现自动生成默认构造函数的概念。每当创建对象时,都会调用默认构造函数。

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

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

因此,此时,编译器将不会插入任何默认构造函数因为类中有有效的构造函数。如果您也需要默认构造函数,则必须自己定义。

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.

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.

深海里的那抹蓝 2024-09-25 09:32:51

还有一种奇怪的情况,您必须定义无参数构造函数。
正如另一位所写,如果您不指定默认构造函数 - 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";
} 
}

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

public class Car extends Vehicle {

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

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

我知道这种情况非常罕见,但我发现了解它很有趣。

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:

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:

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.

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

只有一腔孤勇 2024-09-25 09:32:50

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

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

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

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

勿忘初心 2024-09-25 09:32:50

虽然上面的所有答案都是正确的,但对于新手来说,要理解它有点困难。我会尝试为新人重新回答这个问题。

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

例如,让我们创建一个带有单个参数化构造函数的类 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"
    }
}

哇哈!但是当我们删除 public Student(String name, int rollNo)
构造函数全部完成后,错误消失并且代码可以编译。

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

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

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

变为:

public class Student {

    private String name;
    private int rollNo;

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

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

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

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

参考:Oracle Java 教程

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 Object for a class via a no-arg constructor. This class however has one or more parameterized constructor and this results in a compile time error.

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

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.

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.

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 must also 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.

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

Ref : Oracle Java Tutorial

梦魇绽荼蘼 2024-09-25 09:32:50

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

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.

手长情犹 2024-09-25 09:32:50

这正是预期的行为。

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

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

This is exactly the expected behavior.

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文