什么时候必须在 Java 中使用默认构造函数和参数化构造函数?

Nih*_*rma 4 java constructor

Many a time I have got an exception saying "the default constructor's implementation is missing". And many a times a parameterized constructor's definition alone does everything. I want to know under which conditions this happens.

Jay*_*esh 7

如果类中不存在构造函数,则在编译时添加一个默认构造函数。

如果类中存在任何一个参数化构造函数,则在编译时不会添加默认构造函数。

因此,如果您的程序有任何包含参数的构造函数,并且没有指定默认构造函数,那么您将无法使用默认构造函数创建该类的对象。

例如:

class A{

A(int a){}

}

A a = new A() -----> Error.

-------------------------------------------------------

class A{

A(int a){}

A(){}

}

A a = new A() -----> It will work.

-----------------------------------------------------------

class A{

}

A a = new A() -----> It will work.
Run Code Online (Sandbox Code Playgroud)


Joa*_*uer 6

The compiler doesn't ever enforce the existence of a default constructor. You can have any kind of constructor as you wish.

For some libraries or frameworks it might be necessary for a class to have a default constructor, but that is not enforced by the compiler.

您可能会遇到的问题是,如果您有一个带有自定义构造函数的类,并且您super()的构造函数主体中没有隐式调用。在这种情况下,编译器将引入对超类默认构造函数的调用。如果超类没有默认构造函数,那么您的类将无法编译。

public class MyClass extends ClassWithNoDefaultConstructor
    public MyClass() {
        super(); //this call will be added by the compiler if you don't have any super call here
        // if the super class has no default constructor the above line will not compile
        // and removing it won't help either because the compiler will add that call
    }
}
Run Code Online (Sandbox Code Playgroud)