Working with Java Constructors | Example of Constructor in Java
What time is it? It’s Java time! It is time to learn about Java constructors. We will do that with the help of an example of constructor in Java, and see where a Java constructor fits in the entire coding picture. We will keep layering our example on the go, so as to help you comprehend the ins and outs of everything that surrounds a java constructor.
Java constructor is one of those crucial Object Oriented Programming concepts that we are going to make use of often in the long run.
As you might have guessed already by the name – a constructor, hmmm….it’s constructing something. But what?
A constructor is basically creating an object. When you create an object using the new keyword, you actually “construct” data for the object. So if a class has two variables, creating an object of that class will create an instance that has both the variables initialized to a certain value. If it hasn’t been declared before, then values 0 or Null will be put against them based on their data types.
We will see things more clearly with the help of an example of constructor in Java.
Creating Nay Constructing an Object
Remember how we have been using the constructor all along unknowingly, whilst trying to create an object? Yes, with the new operator and everything? Well, time has come to finally dissect it.
ClassName object = new ClassName();
In the above example when we say “ClassName()”, it is nothing but the constructor we are calling. The constructor executes creating an instance where all fields of a class are provided slots to exist just like a class.
All those blocks in the aforementioned diagram are nothing but fields. An instance or an object is an exact replica of what a class looks like. After initialization in this case not finding anything to initialize the slots on, it puts 0 against any field the class has, and then assigns the block to a variable.
As to why it is deemed crucial for coding, easy there tiger! You are going to find out soon and with an example of constructor in Java.
What is a Constructor?
This brings us to the paramount question of what it really is. A constructor is nothing but a special type of method that we use in order to initialize an object. That part we have already seen so many times!
A couple of points you need to remember whilst working with Java constructors.
- A constructor does not have a return type.
- It has the same name as the class.
- Every class has a constructor. If you don’t see one it is simply hidden. (default constructor)
- A constructor is not a member of a class.
Unlike, how methods are called, a constructor gets automatically called the moment we create an object.
Types of Constructors
To see the syntax of a constructor we need to first understand the types of constructors that are there.
There are two types of constructors:
- Default Constructor
- Parameterized Constructor
The names might have already given away what these java constructors are all about. We will take a look one by one.
Default Constructor
A default constructor is basically responsible for providing default values to objects like 0 or null. It is a type of constructor without any parameters or attributes. A default constructor is created automatically by Java if we do not explicitly create it ourselves. It does not initialize any field and is called if we use the new keyword. The “ClassName()” in the above example was a default constructor.
The syntax to remember for creating a default constructor is:
ClassName() { }
Simply replace ClassName with the same name of the class that you have created. You can choose to use an access identifier as a prefix to the class name. The choice is yours. Inside the braces you can choose to define or display characters as per your requirement. Before we create one simple default constructor, let’s go back to the basics and try to display a simple println message using System.out code.
Calling a Default Constructor
Do you remember how a Class is made up of data members (fields and methods)? That being said it acts as a building block to hold these things taut. If you try to display something inside a class using System.out.println code it would be pointless. Its existence wouldn’t mean a thing. So writing the following code is bound to give you an error:
Java doesn’t understand the existence of a command in a class. It has to be inside a method or there’s no point of writing such a thing. So the above gives you an error.
Hold your horses! We are getting closer to our example of constructor in Java.
Now, since the constructor is nothing but a type of method, putting the above display message inside a constructor should be okay?
Let’s find out:
Now the compile time error is gone. Meaning we are on right track. It’s also quite clear that if we wish to display something in a class, we gotta use its constructor or we will get a compilation error.
But our code doesn’t do anything. As you know, the main() method is our cardinal executor and the control goes directly to it the moment we run our program.
So we will try to call our method, here constructor, to see if we could print the message.
To do so, we will simply create an instance of the Class Eric(), and leave it at that. See that’s one example of constructor in Java.
Creating or Constructing an Instance
Yes you guessed right. The following code:
Eric eric = new Eric();
should call the constructor and do the job.
There! We have got the result too. See? Calling it is a piece of cake.
You can see the warning message telling us we didn’t use the object ‘eric’ anywhere in our code. So it was declared and initialized for nothing. We could use eric to call a method? You know, bring it to good use.
We will try on a different example of constructor in Java.
Initialization and Declaration of Local Variables
I am going to create a method named sink(), and we will use it to display the result of a variable we create in our class. This is to show you that when we instantiate using the constructor, the scope stays limited to whatever goes inside the constructor class.
Creating “int titanic” variable and leaving it undeclared. (Meaning it will have 0 value assigned to it)
Notice how you get 0 when you try to generate what’s in the ‘titanic’ variable? You see when Eric() constructor is called it automatically initializes all its variables to 0 or Null.
When you run the above program you will see how using ‘new Eric()’ has called the constructor, and the control goes to the constructor displaying the message “Up she goes! Up she goes!”, and then comes back to work on eric.sink() and displays 0.
Parameterized Constructor
This takes us to a better and useful example of constructor in Java.
If you provide parameters to your constructor it becomes a parameterized constructor.
So if our class Eric had two fields namely ‘age’ and ‘sex’ one int and the other String respectively, if we try to create an object of such a class, our object is sure to have these fields age and sex inside them right? So, when we create a constructor of such a class these two fields need to be parameterized.
Our constructor will look something like this:
Eric(int a, String s) { age = a; sex = s; }
If you are confused about the working of parameters you can go back to the chapter that teaches how parameters work in Java.
Between the braces, we need to assign the parameters to ‘age’ and ‘sex’ fields. This will help us create an instance where age and sex both are allotted different memory blocks.
Our code will look something like this in Eclipse:
See? This example of constructor in Java looks great already.
Calling via Main and Passing Parameters
When you call the constructor this time you need to provide values for its parameters. So our main method should cover both age and sex up.
Eric eric = new Eric(23, "Yes Please!");
With the above code in the main method, an instance of the Class Eric will be created that will have two blank spaces age and sex created. The values 23 and “Yes Please” then will be put inside it with the constructor execution. Eventually the object reference will be transferred to the variable eric.
We need an additional display method to print things eventually as is. I am going to go ahead and create that method as well and then use it to print whatever we have typed as parameter inputs.
Perfect Example of Constructor in Java
Here the final code will appear something like this:
You can see how we have used eric.display() to call the method display and print the individual variables. If you would have directly printed ‘eric’, you would have got the reference variable address and not the values inside your variables and hence the reroute.
The above example is one perfect example of constructor in Java.
Constructor Overloading in Java
Can a class have just one constructor? No! You can have as many as you want. But how do you differentiate them when they all have the same name? It is via parameters.
Constructor overloading is nothing but a technique to make use of as many constructors as you want. They just differ in terms of parameters.
So I am going to go ahead and create two more constructors in our program to let you get a hang of it properly:
Now it is time to call them, and let Java decide which one we are calling based on the parameter value we put.
Let’s call the first easy one. We don’t need to put any parameters here to call it. A simple
Eric eric = new Eric();
should suffice.
Just put the above code in the main method and run the program to see for yourself if the output “Did you just call me a loser?” showed up or not.
It came right?
Time to call the second and the third one, and display it.
Simply make a slight change to our display method to include ‘friends’ variable. Then append the following two line of codes to the existing main code.
Eric e1 = new Eric(23, "Yes Please!"); Eric e2 = new Eric(17, "No!", 5);
This is how things might appear in your code:
Time to run the program and get the output:
You got the correct output you were looking for. That’s what you had called for. That’s what you got. There are few other concepts around constructor like chaining that we will see once we are through
4 Responses
[…] the case of constructors, when you try to create an instance of a subclass in Java, an instance of the superclass gets […]
[…] lot much easier than it actually might seem. Now that we are already properly introduced to use of constructors and methods, understanding this java keyword would be like a walk in the […]
[…] then distinguished by your JVM with the number of arguments it holds. The same thing we had seen in Constructor Overloading. Remember constructor is nothing but a method […]
[…] Chapter 8 – Java Constructors […]