CodeGym /Courses /New Java Syntax /Initializing objects. Initialize method

Initializing objects. Initialize method

New Java Syntax
Level 10 , Lesson 3
Available

"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."

Example:
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:"

Example with two initialize methods:
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."

Create a copy next to the current file:
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:
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");

String text = file.readText();
MyFile file = new MyFile();
file.initialize("c:\data\", "a.txt");

String text = file.readText();
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");

MyFile file2 = new MyFile();
file2.initialize("a.txt");

String text = file2.readText();

"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."

Comments (63)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Harvey Roberts Level 9, Helsinki, Finland
14 September 2021
The one thing I hate the most is I use English words and not the bastardized versions of Americans, so I get incorrect spelling and when I look mine is fine until I realize 'Colour' and 'Color' GDI!!
Angelica Level 15, New York City, United States
1 July 2021
Why do we declare filename as null? We can we leave it unassigned when we declare it?
Korlat Level 25, Gasteiz, Basque Country, Spain
6 February 2022
I think if you don't assign value to it it is null. private String filename = null; It's the same as: private String filename;
Nathan Guidry Level 6, Lake Charles, United States
15 May 2021
the last examples don't use control sequences..
Nathan Guidry Level 6, Lake Charles, United States
15 May 2021
I mean in the type it out it does nvm nvm
Sinisa Level 11, Banja Luka, Bosnia and Herzegovina
20 February 2021
Here we are skipping some steps in learning by forcing OOP on beginners. Sure, Java is OOP but , but this class mumbo-jumbo creates only confusion because it is forced here before the learning founding bits of every language, such as Arrays and Conditions, which in this course is strangely presented AFTER the OOP. Since OOP gurus like comparisons with the real world, in this manner teaching OOP to beginners BEFORE introducing basic elements like lists/arrays/conditions is analogous to a construction engineer calculating the chimney statics before projecting a building's foundation.
Ajani Level 16, Jacksonville, United States
26 November 2020
hmm most of the Cat's class variables we've dealt with so far have been public. What reason was there to make the MyFile variables private? Dealer's choice?
John Solomon Legara Level 8, Makati, Philippines
6 May 2021
I think learning getters and setters more thoroughly can explain why we want them to be private in general. https://codegym.cc/groups/posts/13-getters-and-setters This was a link from 2 lessons ago and I found it really helpful. Basically, I gathered that having it public will have limitations to your control of the variable and may cause confusion and errors in the future, especially when certain variables have "rules" for it to work. Setting them to private will make it so that only methods can access the variables, and not by the usual Cat.age way of setting them. Read the article, everything gets much clearer.
Mina Level 8, Rome, Italy
11 October 2020
In the third example, he didn't define the getFile() method..why? I didn't understand anything.
Stephen Haokip Level 8, imphal, India
8 June 2020
i fail to understand why we need an initialize method for each variable. i mean can't we just make one initialize for all the class variable.
irades Level 8, Moscow, Russia
30 July 2020
You get better understanding when doing the task with Cats. Cats have 5 variables, but in real life do you always know 5 of them? If it's a homeless cat that you need to add to a list, you probably don't know his name and his age, this is why we need the initialize method that takes 3 arguments. However, if it's a domestic cat, most likely the owner can provide all 5 of the cat's parameters including his name, age, weight, color and address, this is where another initialize method comes to help. In the end we have different cats "on the list", but not all of them have all 5 parameters known. Some cats miss name and address :(
Maryem Vickers Level 7, HT..., United Kingdom
25 August 2020
:<
Rod Johnston Level 0, Melbourne, Australia
11 May 2020
Also struggling right now to understand why you would write an initialize method if a constructor could be used to pass parameters to the object. I'll be patient for now.
Seb Level 41, Crefeld, Germany
17 May 2020
The initialize method is just provided to introduce the concept of how to initialize objects with something we already know (say - how to use a method). Once the constructor is introduced in the following lessons, you'll always be using a constructor to create objects instead. I think it's quite a good way to first show how an object can be initialized with the tools we already know at this stage, and to then introduce an even better and shorter way by using a constructor afterwards. :-)
Lucas Hoage Level 14, Savannah, United States
26 May 2020
I swear, I came to the comments section to ask his same question. At the very least it shows we're grasping the concepts. More importantly I think, as we go along we'll be able to turn to one another for help as we get further along. Much like you just did. Shows that CodeGym's process works.
Stanislav Mayer Level 15, Czech Republic
16 January 2022
The problem here is that the constructors were already introduced in "2.10 - Useful links from the Professor – 2". So we (the students) are already familiar with the constructors concept and we are very confused why to learn some "less elegant" solution for the same situation :-) Still, I agree that it is useful to know both concepts. Only if they introduce this initialization first and only then the Constructors...
Jonaskinny Level 25, Redondo Beach, United States
10 February 2022
It's an established 'best practice' to provide an initialize method so your callers (who don't know anything about your class other than it's public interface) will know the minimum needed to get the instance in a usable 'safe' state. This becomes very useful when doing interface programming calling collections of objects and being able to introspect their initialize method to see what is needed to process them generically as a member of that collection. A car would need (driver, gas, registration) as the minimum for initialization (simple example) ... adding passengers and cargo would be not included in the initialize method in this simple case, but the car's interface (public methods) may allow users to add these optional items. But if your task was looping through all cars in the lot, and get them to the car wash, each would need the minimal initialization parameters. Hope that helps.
Hoist Level 5, San Diego, United States
19 September 2022
the Codegym method works imo. It's a bit quirky but you will laugh when you get further into programming to realize WHY they just focus on 100's of Tasks to grind thru.
12 April 2020
I typed the code entry perfectly and it won't register as complete.
Artur Level 22, Moorends, United Kingdom
12 June 2020
must have missed some space somewhere i had the same once a lesson before there was space between if and () which i omitted :)
Dennis Level 23, Malakoff, United States
1 April 2020
I must admit, the point of the initialization method is lost when you consider the fact that you could simply write a constructor that requires the necessary information. That way user of the class need not remember to call a separate method. But I hear we'll find out in level 05 lecture 08 why we learned about the initialization method.
SirSkii Level 12, Chicago, United States
2 April 2020
I'm actually glad they explained it this way. I just learned about constructors, and yes far better; no reason to create and initialize separately. But I really appreciate learning the 'long way' first. I feel like I fully understand what it means to validate an object having gone through CodeGym's following lessons, then coming back to review.
Jonaskinny Level 25, Redondo Beach, United States
10 February 2022
But if you have multiple constructors, how would you know which one contains the minimal set of parameters needed to get any instance into a safe state for processing? Initialize does this, and constructors can delegate to initialize() (keep an eye out for init() as this is an alternate form of this accepted standard best practice)