"I'd like to tell you about object initialization. When you create an object, you need to assign initial values to its variables to avoid the situation where you access an object that doesn't have the information it needs to work correctly."
"Let's consider a File object. The minimum necessary information for a file is its name. It would be absurd to create a nameless file."
"Suppose we write a MyFile class to work with files. What information would be necessary for each object?"
"The name of the file associated with the object?"
"That's right. To do this, we add the initialize() method to our class. This is how it looks."
class MyFile
{
private String filename = null;
public void initialize(String name)
{
this.filename = name;
}
…
}
"We added the initialize method to make it possible to work with the object by calling the method. We can call the object's methods immediately after calling the initialize method. If we can't work with an object, we call it invalid; otherwise, we say the object is valid. The initialize method's main task is to receive all the data that an object requires to make it valid."
"I see."
"Now let's make our task harder. Or, on second thought, easier. Depends on how you look at it. Suppose a programmer using our class would find it more convenient to pass just the file's directory and short name instead of its full path. We could create another initialize method (Java lets us create several methods with identical names) to let the programmer do this. Here's how our class would look:"
class MyFile
{
private String filename = null;
public void initialize(String name)
{
this.filename = name;
}
public void initialize(String folder, String name)
{
this.filename = folder + name;
}
…
}
"One more thing: we often need to create a temporary copy of a file next to the current one."
"Can we create a method to do this?"
"Sure. Look."
class MyFile
{
private String filename = null;
public void initialize(String name)
{
this.filename = name;
}
public void initialize(String folder, String name)
{
this.filename = folder + name;
}
// The filename will be stored in the same directory as file.
public void initialize(MyFile file, String name)
{
this.filename = file.getFolder() + name;
}
…
}
"And I can make as many of these methods as I want?"
"Well, within reason. But technically speaking, yes, as many as you want."
"When do I have to call the initialize method?"
"Immediately after creating the object, to make it valid."
Examples: |
---|
|
|
|
"What is this getFolder() method?"
"We haven't actually shown the code here. It represents a method that returns a string with the name of the folder where our file is stored."
GO TO FULL VERSION