Java默认构造函数

发布于 2024-10-08 14:42:10 字数 287 浏览 10 评论 0原文

到底什么是默认构造函数 - 您能告诉我以下哪一个是默认构造函数以及它与任何其他构造函数的区别吗?

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;
}

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;
}

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

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

发布评论

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

评论(12

一抹苦笑 2024-10-15 14:42:10

他们都不是。如果您定义了它,则它不是默认值。

默认构造函数是自动生成的无参构造函数,除非您定义另一个构造函数。任何未初始化的字段都将设置为其默认值。对于您的示例,假设类型为 Stringintint,并且类本身是公共的,则看起来像这样

public Module()
{
  super();
  this.name = null;
  this.credits = 0;
  this.hours = 0;
}

:与 完全一样

public Module()
{}

与完全没有构造函数完全一样。但是,如果您至少定义了一个构造函数,则不会生成默认构造函数。

请参阅 Java 规范,特别是:Java 规范部分。 oracle.com/javase/specs/jls/se22/html/jls-8.html#jls-8.8.9" rel="nofollow noreferrer">8.8.9。 Java 语言规范的默认构造函数。

如果类不包含构造函数声明,则隐式声明默认构造函数。顶级类、成员类或局部类的默认构造函数的形式如下:

  • 默认构造函数具有与类相同的访问修饰符,除非类缺少访问修饰符,在这种情况下,默认构造函数具有包访问权限(第 6.6 节)。
  • 默认构造函数没有形式参数,但在非私有内部成员类中除外,其中默认构造函数隐式声明一个表示该类的直接封闭实例的形式参数(§8.8.1、§15.9.2、§ 15.9.3)。
  • 默认构造函数没有 throws 子句。

说明

从技术上讲,默认初始化字段的不是构造函数(默认或其他)。然而,我留下了答案,因为

  • 问题的默认值是错误的,并且
  • 构造函数无论是否包含它们都具有完全相同的效果。

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:

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.

See the Java specifications, specifically: Section 8.8.9. Default Constructor of Java Language Specification.

If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

  • The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (§6.6).
  • The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
  • The default constructor has no throws clause.

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.
请恋爱 2024-10-15 14:42:10

如果您未在类中定义任何构造函数,则会创建默认构造函数。它只是一个不执行任何操作的无参数构造函数。编辑:除了调用 super()

public Module(){
}

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 calling super().

public Module(){
}
我的影子我的梦 2024-10-15 14:42:10

如果您未在类中显式定义至少一个构造函数,则编译器会自动生成默认构造函数。您已经定义了两个,因此您的类没有默认构造函数。

根据 Java 语言规范第三版:

8.8.9 默认构造函数

如果类不包含构造函数
声明,然后是默认值
不带参数的构造函数
自动提供...

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:

8.8.9 Default Constructor

If a class contains no constructor
declarations, then a default
constructor that takes no parameters
is automatically provided...

只是在用心讲痛 2024-10-15 14:42:10

你好。据我所知,让我澄清一下默认构造函数的概念:

编译器自动提供一个无参数的默认构造函数
对于任何没有构造函数的类。这个默认构造函数将调用
超类的无参构造函数。在这种情况下,
如果超类没有无参,编译器会抱怨
构造函数,因此您必须验证它是否有效。如果你的班级没有
显式超类,那么它有一个隐式超类 Object,
它确实有一个无参构造函数。

我从 Java 教程 中阅读了此信息。

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.

I read this information from the Java Tutorials.

蘸点软妹酱 2024-10-15 14:42:10

Java 提供了一个默认构造函数,当未提供显式构造函数时,该构造函数不接受任何参数,也不执行任何特殊操作或初始化。

隐式默认构造函数执行的唯一操作是使用 super() 调用来调用超类构造函数。构造函数参数为您提供了一种为对象初始化提供参数的方法。

下面是包含 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());
    }
}

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

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.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

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());
    }
}
謌踐踏愛綪 2024-10-15 14:42:10

通用术语是,如果您没有在对象中提供任何构造函数,则会自动放置一个无参数构造函数,称为默认构造函数。

如果您确实定义了一个与以下情况下将放置的构造函数相同的构造函数:你不提供任何它通常被称为无参数构造函数。只是一个约定,尽管有些程序员更喜欢将这个显式定义的无参数构造函数称为默认构造函数。但是,如果我们明确定义一个名称,则不会使其成为默认值。

根据文档

如果一个类不包含构造函数声明,则隐式声明一个没有形式参数且没有 throws 子句的默认构造函数。

示例

public class Dog
{
}

将自动修改(通过添加默认构造函数)如下

public class Dog{
    public Dog() {

    }
} 

,当您创建它时object

 Dog myDog = new Dog();

调用此默认构造函数。

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.

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.

一江春梦 2024-10-15 14:42:10

默认构造函数是指在没有任何程序员定义的构造函数的情况下由编译器自动生成的构造函数。

如果程序员没有提供构造函数,编译器会隐式声明一个默认构造函数,该构造函数调用 super(),没有 throws 子句,也没有形式参数。

例如

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

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.

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
淑女气质 2024-10-15 14:42:10

如果一个类没有程序员提供的任何构造函数,那么java编译器将添加一个不带参数的默认构造函数,该构造函数将通过super()调用在内部调用超类构造函数。这称为默认构造函数。

在您的情况下,当您以编程方式添加它们时,没有默认构造函数。
如果您没有添加构造函数,那么编译器生成的默认构造函数将如下所示。

public Module()
{
   super();
}

注意:在默认构造函数中,它还会添加 super() 调用,以调用超类构造函数。

添加默认构造函数的目的:

构造函数的职责是初始化实例变量,如果没有实例变量,您可以选择从类中删除构造函数。但是,当您继承某个类时,您的类有责任调用超类构造函数以确保超类正确初始化其所有实例变量。

这就是为什么如果没有构造函数,java编译器将添加一个默认构造函数并调用超类构造函数。

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.

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.

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.

深海不蓝 2024-10-15 14:42:10

当我们没有显式地为类定义构造函数时,java就会为该类创建一个默认构造函数。它本质上是一个非参数化构造函数,即它不接受任何参数。

默认构造函数的工作是调用超类构造函数并初始化所有实例变量。如果超类构造函数不存在,那么它会自动将实例变量初始化为零。因此,这就是使用构造函数的目的,即初始化对象的内部状态,以便创建实例的代码将拥有一个完全初始化的可用对象。

一旦我们为类定义了自己的构造函数,就不再使用默认构造函数。因此,它们实际上都不是默认构造函数。

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.

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.

陌路终见情 2024-10-15 14:42:10

当您没有在类中定义任何构造函数时,编译器会为您定义默认构造函数,但是当您声明任何构造函数时(在您的示例中您已经定义了参数化构造函数),编译器不会为您执行此操作。

由于您已在类代码中定义了构造函数,因此编译器不会创建默认构造函数。创建对象时,您正在调用默认对象,该对象在类代码中不存在。然后代码就报编译错误。

When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.

Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.

ヤ经典坏疍 2024-10-15 14:42:10

当你创建一个新的 Module 对象时,java 编译器会为你添加一个默认的构造函数,因为根本没有构造函数。

class Module{} // you will never see the default constructor

如果您添加任何类型的构造函数(甚至是非参数构造函数),那么您将拥有自己的 java 构造函数,并且不再添加默认构造函数。

这是一个无参数构造函数,即使您没有父类,它也会在内部调用 super() 构造函数。 (如果您的类没有父类,则将调用 Object.Class 构造函数)

    class Module{

        Module() {} // this look like a default constructor but in not. 
    }

When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.

class Module{} // you will never see the default constructor

If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.

This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)

    class Module{

        Module() {} // this look like a default constructor but in not. 
    }
天煞孤星 2024-10-15 14:42:10

默认构造函数不带任何参数:

public class Student { 
    // default constructor
    public Student() {   

    }
}

A default constructor does not take any arguments:

public class Student { 
    // default constructor
    public Student() {   

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