我正在努力学习Java,我已经设置好了一切,我正在运行。我为我的第一个模型创建了一个构造函数,并设置了一个接受参数的构造函数。我添加了这个功能:
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
Netbeans抛出一个错误,说我需要一个默认构造函数。当我将其更改为:
时,错误消失了。public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
我无法想象这就是在Java中创建可选参数的方式。这就引出了两个问题:
- 为什么我需要一个默认构造函数?
- 如何创建可选参数?
实体类必须有一个无参数的公共或受保护构造函数。
另一种需要无参数构造函数的情况是当您有子类时。
例如,
class Car {
Engine engine;
Car(Engine e)
{
// do something
}
}
你有一个子类,
class Benz extends Car
{
Benz()
{
}
}
Now you can't instantiate a Benz
object. The reason is, when a new Benz()
instantiation is attempeted, the parent constructor is first invoked.
i.e,
class Benz extends Car
{
Benz()
{
super(); //implicitly added
}
}
By default, it tries to invoke a no-arg constructor of the super-class. So you'd need one, unless you have an explicit super(arg) call like this:
class Benz extends Car
{
Benz()
{
super(new Engine());
}
}
Note: A simple Java rule to remember A no-arg constructor is provided by default as long as you don't have another constructor with argument.
i.e
class Car{}
等于class Car{ Car() }
但是当你写
class Car{ Car(Engine e){} }
没有默认的无参数构造函数。您必须显式地编写 class Car{ Car(){} Car(Engine e)}
if you needed it.Yes. Java supports method / constructor overloading.
You don't "need" the default constructor. However, NetBeans is being helpful to you, and informing you that you need one because it assumes you are creating a bean - which requires the option to be created without a constructor requiring parameters - because the calling code wouldn't know what to populate into these.
For "optional" parameters, you can define as many constructors as you would need - with each one omitting one or more of the "optional" parameters.
Why do I need a default constructor?
I think you are trying to call new Guest()
and have only one constructor in Guest class that is Guest(String arg)
. And that's why it is showing error that you need to create a constructor with no arguments that is default constructor of a class.
How do I create optional parameters?
If you want to make a constructor with 0 more arguments you need to use ...
in argument.
Ex:
public class Testing {
public Testing(String... str) {
}
public static void main(String[] args) {
Testing testing = new Testing();
Testing testing1 = new Testing("1");
Testing testing2 = new Testing("2","1");
}
}
如果您正在使用POJO(普通旧Java对象),那么只有在通过调用无参数构造函数(如Guest g = new Guest()
)创建该对象的实例时才需要默认构造函数。
这很明显——你想使用无参数构造函数——你需要有一个。
如果你没有指定任何构造函数,编译器会为你生成一个(默认为无参数)。如果你自己指定了至少一个构造函数,编译器将不会生成任何构造函数,因为它假定你知道自己在做什么。
然而,如果你正在创建一个JPA实体(所以你有@Entity
在你的类的顶部)比你需要一个默认构造函数,因为它是JPA需求。
这是因为当您从数据库中获取类的实例时,该类的实例是由JPA提供程序创建的。JPA提供者必须有一种方法来实例化您的实体。如果您只有参数化的构造函数—JPA将如何知道它应该传递哪些参数?
在Java中没有可选的参数,就像在PHP世界中一样,你可以定义myMethod($var1, $var2 = null, $var3 = 2);
。在Java世界中,我们使用重载方法和变量。