Learn Constructor In Java

Hey guys!! how are you doing!!? Welcome to flower brackets blog. In this post we are going to learn constructor in java.

What is constructor in java?

Constructor in java is used to initialize instance variables of an object. Constructor is similar to method. Basically constructor in java is a method, rather a special method to initialize an object.

Even if you don’t define a constructor it will be there inside your class. Constructor is a member method which has the same name as class name.

NOTE : constructor will never return value.

Syntax:

public class DemoClass
{
   // constructor name is same as class name
   DemoClass()
   {
      ....
   }
}

What is the purpose of a constructor in a class?

  • constructor is used to allocate memory to the object.
  • constructor is used to initialize values.
  • even if you don’t define a constructor, java will create a default constructor whenever you create a class.
  • constructor is the first method which will be executed.

How do you use a constructor?

Say,

public class DemoClass
{
   String webName;
   // Constructor
   DemoClass()
   {
      this.webName = "Flower Brackets";
   }
   public static void main(String[] args)
   {
      DemoClass obj = new DemoClass(); // here i'm mentioning constructor 
      System.out.println(obj.webName);
   }
}

Output:

Flower Brackets

To use constructor, I have created object “obj” of class DemoClass and also I have string instance variable “webName”.

I have passed instance variable “webName” during initialization of constructor. So when object obj is created of class DemoClass constructor gets invoked.

Hence the output “Flower Brackets”. If you notice I have used “this” keyword. this keyword refers to current object.

Also Read – Learn This Keyword In Java

So let’s see an example ,

public class Employee
{
   private String name;
   private int age;

   public Employee(String name, int age)
   {
      this.name = name;
      this.age = age;
   }   
}

In the example above you can see “Employee” class, it has two attributes name and age.

It has one “Employee” constructor which accepts name and age. Using this constructor we can create “Employee” object.

Also Read – Continue Java Example

So, what is the definition of constructors? Constructor is an instance method and sets value for the member object. A class contains special method that are invoked to create objects from the class.

Constructor declarations looks like method declaration except the constructor use the name of the class and constructor has no return type.

Here’s the complete java program on constructor,

public class Employee
{
   private String name;
   private int age;

   public Employee(String name, int age)
   {
      this.name = name;
      this.age = age;
   }
   
   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }

   public static void main(String args[])
   {
      Employee samEmployee = new Employee("Sam", 23);
      System.out.println("Employee Name : " + samEmployee.getName());
      System.out.println("Employee Age : " + samEmployee.getAge());
      System.out.println("----------------------------------");
      Employee benEmployee = new Employee("Ben", 28);
      System.out.println("Employee Name : " + benEmployee.getName());
      System.out.println("Employee Age : " + benEmployee.getAge());
   }
}

Output:

Employee Name : Sam

Employee Age : 23

————————————–

Employee Name : Ben

Employee Age : 28


What are the different types of constructors?

The types of constructors in java is as follows,

  • Default constructor
  • No-argument constructor
  • Parameterised constructor

Let’s see three constructor types with an example

What is default constructor in java?

Constructor without any parameters is known as default constructor. Java automatically creates new default constructor if class does not have or there is no default constructor.

Now what is the purpose of default constructor in java? Let’s see an example with some explanation,

public class Employee
{
   String name;
   int age;
}

In the example above I have defined the class “Employee”. It has two attributes name and age.

public class EmployeeDemo
{
   public static void main(String args[])
   {
      Employee emp = new Employee(); // this is default constructor
      System.out.println("Employee Name : " + emp.name);
      System.out.println("Employee Age : " + emp.age);
   }
}

Output:

Employee name : null

Employee age : 0

As you can see the output default constructor initializes member variables to default values, that is, null and 0. Specifically the purpose of default constructor is to initialize instance variables with fixed values.

No-argument constructor

is constructor with no arguments.

No- Argument constructor example:

class Car
{
   public Car()
   {
      System.out.println("Car created");
   }
}

What is parameterised constructor in java?

Parameterised constructor is a constructor with parameters or arguments. Argument can be of any type, that is, integer, character, array or an object. Here constructor can take any number of arguments.

So let’s see an example,

class ConstructorDemo
{
   // this is default constructor
   ConstructorDemo()
   {
      System.out.println("default constructor");
   }

   // Parameterized constructor : two integer arguments
   ConstructorDemo(int a, int b)
   {
      System.out.println("Parameterized constructor - two parameters");
   }

   // Parameterized constructor : three integer arguments
   ConstructorDemo(int a, int b, int c)
   {
      System.out.println("Parameterized constructor - three parameters"); 
   }

   // Parameterized constructor : one integer and String
   ConstructorDemo(int age, String empName)
   {
      System.out.println("Parameterized constructor - int and string parameter");
   }
}
public class Example
{
   public static void main(String args[])
   {
      // here we are invoking default constructor
      ConstructorDemo cd = new ConstructorDemo();
      // invoking constructor with two arguments
      ConstructorDemo cd1 = new ConstructorDemo(2, 6);
      // invoking constructor with three arguments 
      ConstructorDemo cd2 = new ConstructorDemo(4, 8, 10);
      // invoking constructor with one integer and string arguments 
      ConstructorDemo cd3 = new ConstructorDemo(23, "John");
   }
}

Output:

default constructor
Parameterized constructor – two parameters
Parameterized constructor – three parameters
Parameterized constructor – int and string parameter


What is a private constructor in java?

Private constructor in java prevent class from creating instances from any other part of the (this) class. So, what is the need of private constructor in java?

Yes, we need private constructors. The need of private constructors is to provide singleton classes. Singleton classes limit a class to a single object.

We cannot create more than one object for singleton classes. Let’s understand private constructors and singleton classes in java with an example,

class SingleTonDemoClass 
{
   // this is static class reference
   private static SingleTonDemoClass single = null;
   private SingleTonDemoClass()
   {
      // Private constructor in java prevent class from creating instances
   }
   public static SingleTonDemoClass objMethod()
   {
      // this limit a class to a single object created at a time
      if(single == null)
      {
         single = new SingleTonDemoClass();
      }
      return single;
   }
   public void print()
   {
      System.out.println("calling singleton class");
   }
}
public class PrivateConstructorDemo 
{
   public static void main(String[] args) 
   {
      SingleTonDemoClass object = SingleTonDemoClass.objMethod();
      object.print();
   }
}

Output:

calling singleton class


What is constructor overloading in java?

Constructor overloading is an approach of having more than one constructors in a class with different arguments performing different tasks.

Constructors in java can be overloaded like methods. Let’s see constructor overloading in java simple program,

public class EmployeeData 
{
   private int empID;
   private String empName;

   EmployeeData()
   {
      // this is default constructor
      empID = 10014;
      empName = "John"; 
   }
   EmployeeData(int ID, String name)
   {
      // this is parameterized constructor
      empID = ID;
      empName = name; 
   }

   public int getEmpID() 
   {
      return empID;
   }
   public void setEmpID(int empID) 
   {
      this.empID = empID;
   }
   public String getEmpName() 
   {
      return empName;
   }
   public void setEmpName(String empName) 
   {
      this.empName = empName;
   } 
}

public class ConstructorOverloadingDemo 
{
   public static void main(String[] args) 
   {
      // calling the default constructor
      EmployeeData emp = new EmployeeData();
      System.out.println("Employee name : " + emp.getEmpName());
      System.out.println("Employee id : " + emp.getEmpID());

      // calling overloading constructor 
      EmployeeData emp2 = new EmployeeData(10015, "Charles");
      System.out.println("Employee name : " + emp2.getEmpName()); 
      System.out.println("Employee id : " + emp2.getEmpID()); 
   }
}

Output:

Employee name : John
Employee id : 10014
Employee name : Charles
Employee id : 10015


 

 

Conclusion

This is all about learn constructor in java. I hope you have understood the concept very well.

You can subscribe to my flower brackets if you haven’t already.

Do share this article if you like.

Related Posts