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.
33 Answers
An "empty object" is pretty ambiguous in java terms. I could interpret that as this:
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)
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.
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 (or "unassigned"? depends on the context), but will be of type Name and can be used as such later (once it's assigned a value).
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.
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.
1