在 Java 中创建空对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19918418/
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
Creating empty object in Java?
提问by Java Newb
How do you go about doing this? Is it as simple as this:
你打算怎么做?是不是就这么简单:
Name myName = new Name();
I'm a little confused. It should be a class with no instance variables. I simply have to "create an empty object". The constructor will also be empty of course.
我有点困惑。它应该是一个没有实例变量的类。我只需要“创建一个空对象”。构造函数当然也将为空。
采纳答案by David
If Name
has a parameterless constructor, sure. Whether or not it's "empty" depends on what that constructor does or what defaults it may have.
如果Name
有一个无参数的构造函数,当然。它是否为“空”取决于该构造函数的作用或它可能具有的默认值。
How do you define "empty object" anyway?
无论如何,您如何定义“空对象”?
For example, if you want a variable but don't want it to actually have an object, you can just declare the variable without initializing it:
例如,如果您想要一个变量但不希望它实际上有一个对象,您可以只声明该变量而不初始化它:
Name myName;
In this case myName
will be null
, but will be of type Name
and can be used as such later (once it's assigned a value).
在这种情况下myName
将是null
,但将是类型Name
并且可以在以后使用(一旦它被分配了一个值)。
All the variable itself does is point to a location in memory where the "object" exists. So something like Name myName
doesn't "create" an object, it just creates the pointer to a memory location. new Name()
actually creates an object by calling its constructor. When used together like in your example, the latter half creates the object and then the former half points to the location in memory where the object exists.
变量本身所做的就是指向内存中存在“对象”的位置。所以像这样的东西Name myName
不会“创建”一个对象,它只是创建指向内存位置的指针。 new Name()
实际上是通过调用它的构造函数来创建一个对象。当像在您的示例中一样一起使用时,后半部分创建对象,然后前半部分指向对象所在的内存位置。
回答by SJP
It depends what you mean by empty. What you have done is instantiated an object. If the objects constructor initialized the fields of the Name object then the objects fields have values assigned to them. Also the memory for these fields was allocated when you called new. So even if you havent assigned values to them they do in fact exist in memory but are simply not initialized.
这取决于你所说的空是什么意思。你所做的是实例化一个对象。如果对象构造函数初始化了 Name 对象的字段,则对象字段会分配给它们的值。当您调用 new 时,这些字段的内存也被分配了。因此,即使您没有为它们分配值,它们实际上也存在于内存中,只是没有初始化。
回答by yamafontes
An "empty object" is pretty ambiguous in java terms. I could interpret that as this:
在 Java 术语中,“空对象”非常含糊。我可以这样解释:
Object empty = new Object();
which is about the emptiest object you can create.
这是关于您可以创建的最空的对象。
However in your example,
但是在你的例子中,
Name myName = new Name();
That's going to create an object based on whatever code you've put in your default constructor. (Which, i guess if you're setting everything to a default value, is pretty empty)
这将根据您放入默认构造函数的任何代码创建一个对象。(我想如果您将所有内容都设置为默认值,则非常空)