Constructor Overloading in Java Simple Example

Overview

Constructors in java are used to initialize data members while creating a class. In Java, it is possible to have more than one constructor for a class. Constructors can be overloaded on the basis of the number and type of the arguments.

Scope

  • In this article, we will learn about constructors and their types.
  • We will also talk about the rules that are important while creating a constructor.
  • We will learn about constructor overloading in Java.
  • We will see how constructors are different from class methods.

A constructor is a special member in a class that is called at least once while initializing or creating an object of a class. It is just like a method but without any return type. The main use of this code block is to initialize data members of a class.

Rules for creating Constructors in Java

  1. The constructor's name should match the name of the class.
  2. A constructor cannot have a return type.
  3. A Java constructor cannot use the keywords abstract, static, final, and synchronized.

One should keep these in mind while creating constructors, as not complying with these rules will result in compilation errors. As an example, you can see the error when an abstract keyword is used with the constructor in fig 2.

 Example of an error when abstract keyword is used with constructor

Types of Java Constructors

  1. Default constructor
  2. Parameterized constructor

    There are two types of Constructors in Java

Default Constructor in Java

This type of constructor is called whenever we create an object without passing any argument to the constructor.

Code Snippet 1:

            
                                  public                                                      class                                                      ConstructorEG                                                      {                                    String name;                                                                                            // default constructor                                                      ConstructorEG(){                                      name =                                    "example"                  ;                                                        System.out.println(                  "Constructor called"                  );                                    }                                                                         public                                                      static                                                      void                                                      main                  (String[] args)                                                      {                                                        ConstructorEG object =                                    new                                      ConstructorEG();                                    System.out.println(object.name);                     }                   }                              

Output

            
                                  Constructor called                  example                              

Here in Code Snippet 1 we can see when we create an object with the new keyword the default constructor is called. This default constructor sets the value of the name variable. Default constructors are majorly used to initialize the member variables of an object with some default values

Compiler

This constructor is automatically defined if we don't define any constructor. The compiler automatically generates a default constructor to all classes while compiling. But, if someone defines anyone constructor the compiler will not generate any constructor. So, in case someone defines a parameterized constructor and tries to define an object by MyClass myObject = new MyClass();, it will generate a compilation error because it is trying to call the default constructor which is unavailable. So in this case the user needs to define both the constructors.

Parameterized Constructor in Java

This type of constructor is called if we want to initialize an object by passing a few arguments in the constructor. In this, we initialize some members of the object by passing some parameters as an argument while initializing an object of the class.

Code Snippet 2:

            
                                  public                                                      class                                                      ConstructorEG                                                      {                                    String name;                                                                                            // parameterized constructor                                                      ConstructorEG(String defaultValue){                                      System.out.println(                  "Constructor called"                  );                                    name = defaultValue;                     }                                                                         public                                                      static                                                      void                                                      main                  (String[] args)                                                      {                                                        ConstructorEG object =                                    new                                      ConstructorEG(                  "custom value"                  );                                    System.out.println(object.name);                     }                   }                              

Output:

            
                                  Constructor called                  custom value                              

Here we can see, while creating an object with the new keyword, we passed a String , this value is then set to the data member of the class i.e. name.

Constructor Overloading in Java

Till now we know how different Java constructors work. We know that constructors are similar to methods but they don't have return types. Also, we can pass arguments while calling both. If we look closely all the constructors are of the same name, but the only difference is the argument part. Doesn't it look like the constructors are being overloaded? Yes, it is. Since both, the constructor has the same name but different arguments, they show compile-time polymorphism i.e. overloading. Not only this, we can even overload parameterized constructors based on the number and type of arguments as can be seen in code snippet 3, the parameterized constructor 1 and 2 are overloaded. Let's check an example

Code Snippet 3:

            
                                  public                                                      class                                                      ConstructorEG                                                      {                                    String name;                     Integer number;                                                         ConstructorEG(){                                    // default constructor                                                                          System.out.println(                  "Default Constructor called"                  );                                    }                                                         ConstructorEG(String defaultValue){                                    // parameterised constructor 1                                                                          System.out.println(                  "Parameterized Constructor for name called"                  );                                    name = defaultValue;                     }                                                         ConstructorEG(Integer number){                                    // parameterised constructor 2                                                                          System.out.println(                  "Parameterized Constructor for number called"                  );                                                                        this                  .number = number;                                    }                                                                                                               public                                                      static                                                      void                                                      main                  (String[] args)                                                      {                                                        ConstructorEG object =                                    new                                      ConstructorEG(                  "custom value"                  );                                    System.out.println(object.name);                                                                                ConstructorEG object2 =                                    new                                      ConstructorEG(                  123                  );                                    System.out.println(object2.number);                     }                   }                              

Output:

            
                                  Parameterized Constructor                                    for                                      name called                  custom value                  Parameterized Constructor                                    for                                      number called                                                      123                                                                  

Here in this example, we can see both types of the constructor are defined in the same program and Since we are passing arguments while creating the object, the parameterized constructor is called. There are times when the default constructor needs to be called from a parameterized constructor, then this() is used. We can call the default constructor from the parameterized constructor using this() method.

Note: In case someone wants to call the default constructor, then, this() should be the first statement in the block else, the compiler will throw a compilation error.

Code Snippet 4:

            
                                  public                                                      class                                                      ConstructorEG                                                      {                                    String name;                     Integer number;                                        ConstructorEG(String defaultValue){                                                      this                  ();                                                        System.out.println(                  "Parameterized Constructor for name called"                  );                                    name = defaultValue;                     }                                        ConstructorEG(Integer number){                                      System.out.println(                  "Parameterized Constructor for number called"                  );                                                                        this                  .number = number;                                    }                                        ConstructorEG(){                                      System.out.println(                  "Default Constructor called"                  );                                    }                                                                         public                                                      static                                                      void                                                      main                  (String[] args)                                                      {                                                        ConstructorEG object =                                    new                                      ConstructorEG(                  "custom value"                  );                                    System.out.println(object.name);                                                                                ConstructorEG object2 =                                    new                                      ConstructorEG(                  123                  );                                    System.out.println(object2.number);                     }                   }                              

Output:

            
                                  Default Constructor called                                    Parameterized Constructor                                    for                                      name called                  custom value                  Parameterized Constructor                                    for                                      number called                                                      123                                                                  

Here we can see, we called the parameterized constructor, but, since we called the default constructor using this() from the first line of the parameterized constructor, the default constructor execution completes first.

Difference between constructor and method overloading in Java

  • Constructor is used to initialize an object whereas a method is used to perform certain functions of a class.
  • Constructors are invoked implicitly when an object is created whereas methods are called explicitly by the user.
  • Constructors don't have a return type whereas methods have a return type of either a type of Object or void.
  • Constructor should have the same name as that of the class whereas method name should not be of the same name as that of class.

Copy Constructor in Java

Copy constructors help in initializing an object by copying data value from another object of the same class. You can consider it like cloning an existing object to create a new copy. Unlike C++, Java doesn't have default support for copy constructors, but we can implement a copy constructor of our own using a parameterized constructor. Here is how we will do this

Code Snippet 4:

            
                                  public                                                      class                                                      ConstructorEG                                                      {                                    String name;                                        ConstructorEG(ConstructorEG original){                                      System.out.println(                  "Parameterized 1 Constructor called (COPY CONSTRUCTOR) "                  );                                    name = original.name;                     }                     ConstructorEG(String name){                                      System.out.println(                  "Parameterized 2 Constructor called"                  );                                                                        this                  .name = name;                                    }                                                                         public                                                      static                                                      void                                                      main                  (String[] args)                                                      {                                                        ConstructorEG object =                                    new                                      ConstructorEG(                  "custom value"                  );                                                        System.out.println(                  "Original object - "                                      + object.name);                                                        ConstructorEG newObject =                                    new                                      ConstructorEG(object);                                                        System.out.println(                  "Copied object - "                                      + newObject.name);                                    }                   }                              

Output:

            
                                  Parameterized                                    2                                      Constructor called                  Original object - custom value                  Parameterized                                    1                                      Constructor called                  Copied object - custom value                              

We can see in this example, we create an object with a name as a custom value. Then we passed this object as an argument to the copy constructor (implemented through a parameterized constructor). When we print the value of the name in the newly copied object, we can see that the name is also copied to the new object newObject.

Copying values without constructor

By this time we know how copy constructors work. But, we can clone an object in Java without using a copy constructor too. In other words, we can copy the values of one object to another without the use of a copy constructor. Since we have to implement our own logic in the copy constructor we can see that this logic need not necessarily be placed in a constructor. We can place the code logic anywhere we need. Let's do this with an example.

Code snippet 5:

            
                                  public                                                      class                                                      ConstructorEG                                                      {                                    String name;                                        ConstructorEG(){                     }                                        ConstructorEG(String name){                                                      this                  .name = name;                                    }                                                                         public                                                      static                                                      void                                                      main                  (String[] args)                                                      {                                                        ConstructorEG object =                                    new                                      ConstructorEG(                  "custom value"                  );                                                        System.out.println(                  "Original object - "                                      + object.name);                                                        ConstructorEG newObject =                                    new                                      ConstructorEG();                                                        newObject.name = object.name;                                    //line number 22                                                                          System.out.println(                  "Copied object - "                                      + newObject.name);                                    }                   }                                                 

Output:

            
                                  Original object - custom value                  Copied object - custom value                              

Here in the code snippet 5 , we can see in line number 22, we have explicitly copied the value of the name in the newly created object newObject. This is how we can copy values without the use of a copy constructor.

Conclusion

In this article, we saw how we can define and overload constructors in Java. Java doesn't support copy constructor by default but we can implement it by using a parameterized constructor. Here are some of the use cases where to use which constructor.

Usage:

  • The default constructor is used to initialize the default values of data members of the class.
  • The parameterized constructors can be used to create a copy of an object.
  • Parameterized constructors are also used to set member variables of an object while initializing. :::

stowbeemame.blogspot.com

Source: https://www.scaler.com/topics/constructor-overloading-in-java/

0 Response to "Constructor Overloading in Java Simple Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel