如何最好地解释和使用 Java 中的空构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18993936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to best explain and use empty Constructors in Java?
提问by Sophia Ngo
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:
我一直在自学Java。我了解定义类的范围,但仍然没有得到空构造函数用法的概念。
通常我们应该为构造函数传递参数来构建实例对象。但是,我经常看到构造函数的参数为空。例如:
class Person {
String name;
int age;
public Person();
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
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:
我研究并阅读了一个使用“fish”类来解释的例子。所以,这就是我到目前为止所理解的:在定义一个类时,我们首先为一个对象定义属性,然后我们创建一个构造函数,该构造函数将使用方法构建该对象。空构造函数构建 GENERIC 对象,带参数的构造函数构建具有更具体信息的对象。让我们说上面的例子,如果我使用空构造函数创建一个实例对象:
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?
-- 它仍然会创建一个对象,但其中没有任何属性?那么,空构造函数到底是用来做什么的呢?我在很多示例代码中看到了它。它非常有用/常见吗?
Thanks for looking and answering!
感谢您的关注和回答!
回答by porfiriopartida
An empty constructor usually is "a default"
空构造函数通常是“默认值”
Person() {
// This will cause you to not have any name or age values
}
So let's assume you want a default Person:
所以让我们假设你想要一个默认的 Person:
Person() {
this("Steven",20);
}
This way you will call the non empty constructor but you will always have the same person
这样您将调用非空构造函数,但您将始终拥有同一个人
回答by tbodt
There are three common reasons to define a default constructor:
定义默认构造函数的三个常见原因:
- To construct an object with default values.
- To initialize an object that doesn't need parameters in that initialization process.
- To redefine the scope of the constructor. Making the constructor private will prevent anyone but the class itself from constructing an object.
- 构造具有默认值的对象。
- 初始化一个在初始化过程中不需要参数的对象。
- 重新定义构造函数的作用域。将构造函数设为私有将阻止除类本身之外的任何人构造对象。
回答by tmh
Whether you define an "empty" (default) constructor or not allows you to make clear to yourself and other developers, if certain fields are required to be set or not. (If the constructor demands them, they're required.)
无论您是否定义“空”(默认)构造函数,您都可以向自己和其他开发人员说明是否需要设置某些字段。(如果构造函数需要它们,则它们是必需的。)
Some libraries (for example Google GSON, ORMs ...) require you to have an empty constructor, but that's rather for technical reasons.
一些库(例如 Google GSON、ORMs ...)要求您有一个空的构造函数,但这是出于技术原因。
Another thing to keep in mind is that you can usually declare the fields assigned through a constructor as final
, both for optimization and to make clear that they won't change during the object's lifetime.
要记住的另一件事是,您通常可以将通过构造函数分配的字段声明为final
,以进行优化并明确它们在对象的生命周期内不会更改。
But that all depends on the situation and what you're trying to do.
但这一切都取决于情况和您要尝试做什么。
回答by RandomQuestion
I am sure other answers would come but in short -
我相信会有其他答案,但简而言之-
Empty constructor just gives you an instance of that object. You might use setters on it to set necessary properties. If you want to make sure that any instance created is always valid and any member variables are always initialized,then you would define the constructor which initializes all the required member variables.
空构造函数只为您提供该对象的实例。您可以在其上使用 setter 来设置必要的属性。如果要确保创建的任何实例始终有效并且始终初始化任何成员变量,则应定义初始化所有必需成员变量的构造函数。
Also if you use frameworks like Spring, default constructor is often used where properties are set using setter injection.
此外,如果您使用 Spring 等框架,则通常在使用 setter 注入设置属性的情况下使用默认构造函数。
回答by jsedano
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;
}
}
You can'tdo this now:
你现在不能这样做:
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;
}
}
回答by Affe
A lot of software written in java these days takes advantage of frameworks that operate directly on your code at runtime by using special JVM features (known as reflection) to just access your class directly and mess around with it, rather than access it through the code you actually wrote.
如今,许多用 Java 编写的软件利用了在运行时直接对代码进行操作的框架,通过使用特殊的 JVM 功能(称为反射)来直接访问您的类并对其进行处理,而不是通过代码访问它你真的写了。
One common example of such a library is Hibernate. It "magically" takes information from a relational database and assigns the database values to the fields of an object. Your class is enhanced with additional code added at run time to make it magically map back to the contents of the database.
此类库的一个常见示例是 Hibernate。它“神奇地”从关系数据库中获取信息并将数据库值分配给对象的字段。您的类通过在运行时添加的附加代码得到增强,使其神奇地映射回数据库的内容。
It is a consequence of the reflection API that it's a real pain in the butt to work with classes that do not have a 'default' constructor. You would have to supply a lot of additional information about how to correctly use your class's constructors in a way that can be programmatically interpreted.
反射 API 的结果是,使用没有“默认”构造函数的类真的很痛苦。您将必须提供大量关于如何以可以编程方式解释的方式正确使用类的构造函数的附加信息。
Instead, the tools just require that classes have an empty, default, constructor, to make it easy to enhance the class at runtime.
相反,这些工具只要求类有一个空的默认构造函数,以便在运行时轻松增强类。
Hence, we tend to leave an empty constructor always, even when creating an object without supplying certain values doesn't really make sense according to our program's API.
因此,我们倾向于总是留下一个空的构造函数,即使根据我们程序的 API,即使在不提供某些值的情况下创建对象也没有真正意义。