Scientech Easy Java Constructor: Default & Parameterized with Example | Scientech Easy

Tuesday, July 3, 2018

Java Constructor: Default & Parameterized with Example

In this tutorial, we will learn a very interesting and easy topic Constructor in Java and its types Default & Parameterized Constructor with example and it is the very important topic in the Java. You will learn here Constructor like a pro.

Constructor in Java

When you create an object of a class using the new operator, you invoke(calls) a special kind of method called a constructor just after the memory allocated for that object. In other words, we can also say that Constructor in Java is a block of code within a class that allows creating object of the class.

Syntax:
      Access modifiers_name  class_name(Parameter_list) // const. starts.
          {
                // Constructor body which is a block of statements where you can initialize the values of instance variables, local variables, call the methods, and print output. 
             
              } // End of const.     
Example:
        public Rectangle(int l, int b) {
               lenght=l;
               breadth=b;
              }
                                                         
A constructor is a special method whose name is same as that of the class name and it is called when you use the new operator.
Consider the following example:
                School sc=new School();
 Where
             School ➝ name of the class.
                 sc     ➝ Object reference variable which stores the address of the object in the stack memory.
          School() ➝ Constructor of the class.
             new     ➝ is a special keyword that allocates the memory to store the object whose type is specified by a constructor and then calls the constructor to initialize the object, which is stored in the heap( a region of memory for storing objects). When constructor ends, new return memory addresses to the object so that it can be accessed from anywhere in the application.

➲ A constructor in Java is used to perform initialization of instance variables of a class. 
➲ The constructor should not have any return type even void also because if there is return type then JVM would consider as a method, not a constructor. Compiler and JVM differentiate constructor and method definitions on the basis of the return type.
Suppose you define the method and constructor with the same name as that of the class name then JVM would differentiate between them by using return type.


When we create the object then the constructor will be automatically called by the JVM.
If you don't define any constructor, the compiler automatically creates a default constructor and assign default values for all your variables in the class.
java constructor,constructor in java with example,Java class constructor, Default constrcutor, Parameterized constructor, Constructor programs, uses of constructor.
Constructor in Java

Types of Constructor in Java

1. Default Constructor
2. Parameterized Constructor

Default Constructor(non-argument constructor) in Java

A constructor which have no parameter is known as default constructor. A constructor is called default only if it is created by the compiler.
Note: We cannot pass any argument to the default constructor. That's why it is called non-argument constructor.

Let's take an example to understand the default clearly.

Let's have a class Person. A person has three major properties like name, age, and address. where the name, age, and address are instance variables.
Program 1:

    package scientecheasy; public class Person { // Declaration of Instance variables. String name; int age; String address; // Here, We are not creating any constructor. So Compiler will automatically insert the default constructor. // Create one method to print the default values. void display(){ System.out.println(name+ " " +age+ " " +address ); } // Static method or main method. public static void main(String[] args) { // Create the object of the class using new keyword. Person p=new Person(); // Call the method using object reference variable p. p.display(); } }
    Output: null 0 null
In the above example, we did not create any constructor so compiler provides the default constructor. null, 0, null is the default values of the instance variables provided by the default constructor

Now we can use the default constructor to initialize the values of instance variables. So if you put default constructor then the compiler will not insert any constructor.
Let's see.
Program 2:
    package scientecheasy; public class Person { // Declaration of Instance variables. String name; int age; String address; // Now create the default constructor. Person() { // Initialization of values of Instance variables. name="Vivek"; age=25; address="Gandhi Nagar"; //Print the values. System.out.println(name+ " " +age+ " " +address); } // Static method or main method. public static void main(String[] args) { // Create the object of the class using new keyword. Person p=new Person(); } }
    Output: Vivek 28 Gandhi Nagar.
Now let's see the memory detials behind the constructor. See below image.
java constructor,constructor in java with example,Java class constructor, Default constrcutor, Parameterized constructor, Constructor programs, uses of constructor.
Java Constructor 

You know that p is a object reference variable which contains address of the memory location of the object. Here, 5575 is the address on the stack where you can find other detail of the class like name, age, and address on this address.  So you always remember that reference variable never contains object directly. It contains address which points to data stored in the memory location. You can see the above image that when we did not initialize the values of the instance variable in the constructor in the program 1 then default values are stored on the heap after calling constructor but 
when we initialized the values in the constructor in the program 2 then after calling the constructor, default values are eleminated and initialized values are stored in the memory location of heap.

Parameterized Constructor in Java

➲ A cosntructor which have parameter is known as parameterized constructor or argument constructor. Parameterized constructor is used to provide different values to the distinct object. 
➲ In the parameterized constructor, we pass the parameters while creating the object. 
➲ Argument can be of any type i.e Integer, array, character or an object.
➲ It can take any number of arguments.
➲ Java does not provide a parameterized constructor by default.
Example:
       School sc=new School("RSVM", 20, "Dhanbad");
Let's take a good scenerio.
Program 3: 

    package construtor; public class Student { // Declaration of Instance variables. String name; String schoolName; int std; String city; // There are two types to declare the parameterized constructor. // First type: public Student(String name, String schoolName, int std, String city) { //Here, The parameter's indentifier is same as that of the variables name. It is permissible to do this in Java. // The 'this' refers to the current object, the '.'called attribute's identifier select the variables name, schoolName, std, city from the current object. The '=' is the argument's identifier. System.out.println("Constructor called.."); this.name=name; this.schoolName=schoolName; this.std=std; this.city=city; } // Second type public Student(String n, String scn, int s, String c){ // Here, The name of the parameter is different from the name of the variables that it sets. // Therefore, we don't need to refer to the current object with 'this'. name=n; schoolName=scn; std=s; city=c; } // Create the method to print the output. You can also print the output inside the constructor. void display(){ System.out.println(name+ " " +schoolName+ " " +std+ " " +city); } // main method. public static void main(String[] args) { // Create the object of the class and pass the values to the constructor. Student s=new Student("Ankit", "RSVM", 12, "DHANBAD");// Const. called. // Call the display method to get the output. If you don't call then display method will not give output. s.display(); } }
    Output: Constructor called.. Ankit RSVM 12 DHANBAD

Difference between constructor and method

 Constructor is used to initialize the state of an object whereas Method is used to expose the behaviour of an object.
 It has no return type even void also wheras method has both void and return type.
If you don't provide any constructor then compiler provides the default constructor whereas Method is not provided by the compiler in any case.
 Constructor name must be same name as that of the class name whereas Method name may or may not be the same name as the class name.

What are the real use of Constructor in Java?

➝ Constructor is used to assign the deafult values of instance variables.
➝ Private cosntructor is used in singletone classes where object of the class cannot be created outside the class. 

Important points to remember

When you create an object, its constructor is called before any methods.
When you dont't define a constructor, Java provides its own default constructor.
If you define your own constructor then you have to decide what values should be given to the instance variables.
Constructor can have any access modifiers like private, public, protected or default.
this() and super() must be first line in the constructor code.
Constructor overloading is possible but overridding is not posiible.

It cannot be inherited.
A constructor can also call another constructor of same class using 'this' and for agrument constructor use 'this(para_list)'. 
A Constructor is not keyword in Java.

Final words:
I hope this article help you to understand the Constructor in Java and types Default Constrcutor and Parameterized constructor with examples. In next tutorial I will explain some important points with programs.

Other Topics
1. Java constructor overloading Tutorial
2. Constructor chaining in Java with example programs


Next ➝ Constructor overloading                                                              Scientech Easy loves you 


Popular