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.

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 to use constructor?

For example

public class DemoClass
{
   String webName;
   // Constructor
   DemoClass()
   {
      this.webName = "Flower Brackets";
   }
   public static void main(String[] args)
   {
      DemoClass obj = new DemoClass(); // calling 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 another 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 class “Employee” 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

Here’s the complete java program,

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


Types of constructors

  • Default constructor
  • No-argument constructor
  • Parameterised constructor

Default constructor

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 class “Employee”. It has two attributes name and age.

public class EmployeeDemo
{
   public static void main(String args[])
   {
      Employee emp = new Employee(); // 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. The purpose of default constructor is to initialize instance variables with fixed values.

No-argument constructor

No-argument constructor is a constructor with no arguments.

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

Parameterised constructor

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.

class ConstructorDemo
{
   // 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 : 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


Private constructor

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?

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 
{
   // static class reference
   private static SingleTonDemoClass single = null;
   private SingleTonDemoClass()
   {
      // Private constructor in java prevent class from creating instances
   }
   public static SingleTonDemoClass objMethod()
   {
      // limits a class to a single object
      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


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,

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

   EmployeeData()
   {
      // default constructor
      empID = 10014;
      empName = "John"; 
   }
   EmployeeData(int ID, String name)
   {
      // constructor overloading
      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 default constructor
      EmployeeData emp = new EmployeeData();
      System.out.println("Employee name : " + emp.getEmpName());
      System.out.println("Employee id : " + emp.getEmpID());

      // calling overloaded 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

Related Posts