Constructors

New Java Syntax
Level 10 , Lesson 5
Available

A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.


"Now it's high time that I tell you about constructors. This is really simple concept. Programmers have invented a shorthand way to create and initialize objects."

Without a constructor With a constructor
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");
String text = file.readText();
MyFile file = new MyFile("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("c:\data\", "a.txt");
String text = file.readText();
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");

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


MyFile file2 = new MyFile(file, "a.txt");
String text = file2.readText();

"I just finished learning about the initialize method…"

"Look harder. With constructors, the code is more convenient and compact."

"So it is. Here's a question. I know how to write an initialize method inside a class, but how do I write a constructor?"

"First, look at this example:"

Without a constructor With a constructor
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;
  }

  public void initialize(MyFile file, String name)
  {
    this.filename = file.getFolder() + name;
  }

…
}
class MyFile
{
  private String filename = null;

  public MyFile(String name)
  {
    this.filename = name;
  }

  public MyFile(String folder, String name)
  {
    this.filename = folder + name;
  }

  public MyFile(MyFile file, String name)
  {
    this.filename = file.getFolder() + name;
  }

…
}

"It's easy to declare a constructor inside a class. A constructor is similar to the initialize method, with just two differences:

1. The name of a constructor is the same as the class name (instead of initialize).

2. A constructor has no type (no type is indicated)."

"OK, so it's like initialize, but with a few differences. I think I get it."

Comments (36)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Lomd Level 2, Curitiba, Brazil Expert
24 July 2023
So, to the best of my understanding Constructors are indeed initialize methods, with just a few albeit key differences. 1. They are automatically of type "void", which is to say, they return no value; 2. They are named after the Class itself; 3. They are invoked automatically when the new instance of the object is created. Strictly speaking they are not a necessary part of the language. But they sure lead to less tedious coding and less vulnerability to mistakes.
Rebecca Zee Level 10, New York, United States
22 June 2023
I don't get the difference where it is comparing using a constructor vs without a constructor. It makes no sense to me since a constructor is still being called when there are no arguments. It looks like they are comparing a default constructor vs an overloaded constructor. Just because at time of creation, the object does not pass in any data, that does not mean there is no constructor.
Angelo Tratsis Level 8, Boston, United States
15 April 2021
I love the step by step in CodeGym. You guys rock, genius way to learn.
what??? Level 20, Taiwan, Province of China
17 September 2022
true
ImDevin Level 15, Old Town, United States
6 April 2021
I think codeGym had us do the initialize methods first to just used to the idea how or what purpose Constructors are used for, mainly, to initialize Instance Variables. By now, we're used to the idea of initializing variables and we just need to apply it to Constructors and use it going forward.
6 January 2021
I really don't understand the difference between constructor and inizialize method. When I have to use one instead of other? or contructor is just a compact inizialize method?
Ahmad Level 7, Detroit, United States
24 March 2021
The main difference is initialize method is used AFTER you already created the object. Constructor is used at the time of creating the object. So it depends if you need your instance variables at the time of creating the object, or after the object has already been created. Most programs I've seen in Java mainly use the constructor. I barely ever see initialize being used. Hope this helps.
Jonaskinny Level 25, Redondo Beach, United States
11 February 2022
Some Frameworks will use initialization extensively. Anything where you have ... ServiceClass someServiceClass = Class.forName("com.yourcompany.projectname.package.classname).newInstance(); someServiceClass.initialize() <-- this initialize method can then call another set of Class.forName methods, or do some other initialization using system properties or other means to 'initialize' the classes using a given environment ... so if the above was a database connection, it could get initialized with database name, url, uname, password, etc. This keeps the config out of the code, lets the framework instantiate the objects via default means (caller does not need to know about what database is used on the back end, just need it to get initialized to 'some' database), and allows the framework to keep track of object state (so if an error occurred during initialization for example, the someServiceClass could have a .isSafeToUse method that would be set to false initially, then only set to true if all initialization steps were successful, otherwise the caller would know not to use it without needing to know how to use it. We can also use static code blocks for this, eliminating the need for the caller to interact with the framework code.
P.B.Kalyan Krishna Level 22, Guntur, India
16 February 2024
initialize() is shown just to highlight the importance of constructors. With initialize() you must initialize the object deliberately after an object is created. If you forget to call the initialize(), your object remains uninitialized thus becoming invalid. Whereas with a constructor the object is initialized at the time of object creation. The constructor forces you into object initialization at the time of object creation. Otherwise, the object is not even created. In real life initialize() methods are rarely used. Object initialization is done through constructors.
Ibrahim Level 9, Minneapolis, United States
24 August 2020
what a short, helpful way to introduce constructors! Most textbooks take a long way of introducing constructors and only then explaining their functionality.
Maryem Vickers Level 7, HT..., United Kingdom
25 August 2020
Yes Ibraheem, very annoying textbook methods they have... *sigh*
Abdullah Level 8, Doncaster, United Kingdom
5 June 2021
Aye textbook learning can be daunting. :p
bob Level 8, Milan, Italy
26 May 2020
i haven't ever used initialize, only constructors, but what is the real benefit of constructors over initialize other than typing a couple less words?
bob Level 8, Milan, Italy
27 May 2020
found answer here... https://codegym.cc/groups/posts/constructors-in-java
Peter Schrijver Level 23, Hilversum, Netherlands
23 May 2020
Nice introduction how to work with constructors
Uchenna Benjamin Level 15, Madisonville, United States
28 March 2020
i love this lesson well broken down.
Larisa Alexa Level 20, Iasi, Romania
10 March 2020
Which are the cases in which constructors should be used?
Dennis Level 23, Malakoff, United States
1 April 2020
In reality, you will likely always use constructors instead of the initialize method. This forces the user of a class to initialize the instance with the correct information, as opposed to hoping they remember to call the initialize method. In my years as a professional software developer, I've honestly never seen the initialize method used. Take a look through some Java projects on GitHub and I'm sure you'll be able to confirm this.
Jonaskinny Level 25, Redondo Beach, United States
11 February 2022
Look for frameworks that use a ServiceLocator pattern or similar. Some would use initialize (or init()) extensively.