如何最好地解释和使用 Java 中的空构造函数? [英] How to best explain and use empty Constructors in Java?
问题描述
我一直在自学Java.我了解定义类的范围,但仍然没有得到空构造函数用法的概念.
通常我们应该为构造函数传递参数来构建实例对象.但是,我经常看到构造函数的参数为空.例如:
I have been self-learning Java. I understand the scope of defining a class, but still didn't get the concept of an empty constructor usage.
Usually we should pass parameters for constructor to build instance object. But, I often see empty parameter for constructor. For example:
class Person {
String name;
int age;
public Person();
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
我研究并阅读了一个使用fish"类来解释的例子.所以,这就是我目前所理解的:在定义一个类时,我们首先为一个对象定义属性,然后我们创建一个构造函数,该构造函数将使用方法构建该对象.空构造函数构建 GENERIC 对象,带参数的构造函数构建具有更具体信息的对象.比如说上面的例子,如果我使用空构造函数创建一个实例对象:
I researched and read an example that using a class "fish" to explain. So, this is what I understood so far: when defining a class, we first define properties for an object, then we create a constructor that will build the object with methods. Empty constructor build GENERIC object, and constructor with parameters build objects with more specific information. Let’s say the example above, if I create an instance object using the empty constructor:
Person p1 = new Person();
-- 它仍然会创建一个对象,但其中没有任何属性?那么,空构造函数到底是用来做什么的呢?我在很多示例代码中看到了它.它非常有用/常见吗?
-- it will still create an object but without any properties in it? So, what exactly the empty constructor is used for? I saw it in a lot of example codes. Is it very useful/common?
感谢您的关注和回答!
推荐答案
如果你写了一个带参数的构造函数,那么你需要声明默认的(如果你想使用它)
If you write a constructor with parameters, then you need to declare the default one (if you want to use it)
class Person {
String name;
int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
您现在不能这样做:
Person p = new Person();
为了使用默认"构造函数(不带参数),您需要声明它:
In order to use the "default" constructor (with no parameters) you will need to declare it:
class Person {
String name;
int age;
public Person(){
name = "Man With No Name"; //sometimes you will want to set the variables
age = 21; //to some default values
}
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
这篇关于如何最好地解释和使用 Java 中的空构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!