Constructors in Java

Beginners code Computer Skills Java Mobile Development Web Development

What are Constructors in Java?

Constructors are a special type of blocks that help to initialize an object. The JVM invokes the constructor at the time of object creation. Thus constructor in Java is an important part of class.

Now you might be wondering, how we have been creating objects from the very beginning of this tutorial without defining any constructors?!

This is because, if there are no explicit constructor definitions in the program, then the Java compiler automatically provides a default constructor.

For example,

Student object= new Student();

new Student() is the default constructor provided by the compiler.

Rules for Creating a Constructor:

  • Constructor name should always be the same as the name of the class.
  • It never returns any value. So it does not have a return type.
    • If there is a return type for the constructor, JVM treats it as an ordinary method.
  • A constructor should not be static.
    •  JVM will call the constructors each and every time whenever an object is created.
    • This is because the objects should be able to hold different copies of data values for different objects.
  • Constructors should not be private.
    • When an object of one class is created in another class, a private constructor will not be visible to the other class and hence there will be a compilation error.
    • It can be private if an object of the class is created only inside that same class.
    • Constructors will not be inherited at all.

Difference between Method and Constructor:

Although a constructor looks like a method, they are different in many ways. Following are the differences between methods and constructors.

MethodConstructor
Method name may or may not be the same as the class nameConstructor name must be the same as the class name
Should have a return typeNever returns any value. So no return type
Can be called directly, by class name or by object name.Can only be called by new keyword.
Can be declared as static.Static keyword is not allowed for a constructor.
May or may not be declared as Abstract.Abstract keyword is not allowed for a constructor.
Can be overridden in Java.Cannot be over-ridden.
It is not provided by the compiler in any case.Java compiler provides a default constructor if there is no constructor defined.

The below program will help you understand the differences between a method and a constructor.

package mypackage;

public class ConstructorTest {

  public ConstructorTest() {
    System.out.println(" Default constructor block");
  }
  
  
  public ConstructorTest(int x) {
    System.out.println(" Parameterized constructor block with value as " + x );
  }
  
  static void DisplayMessage() {
    
    System.out.println(" Display Message method ");
  }
  
  public static void main(String[] args) {
    
    //Constructor called with new keyword
    new ConstructorTest();
    new ConstructorTest(100); 
    
    DisplayMessage(); // method called directly
    ConstructorTest.DisplayMessage(); // method called with class name

  }
}

Output:

constructors and method output

Types of Constructor:

Java supports 2 types of constructors:

Default Constructor:

  • A default constructor does not have an argument.
  • It provides default values to the object.
  • If no constructor is designed by the user explicitly, java compiler implicitly provides a default constructor.
    • JVM calls that system defined default constructor at the time of object creation.
  • If we define a default constructor, JVM will call the user-defined default constructor.
package mypackage;

public class StudentGroup {
  
  String studentname;
  int studentid;
  double studentsalary;
  
  public StudentGroup() {
   System.out.println("default constructor");	
  }

  void display()
  {
    System.out.println("All the details of the student are: " + studentname+ ", "+studentid+", "+studentsalary);
  }
  
  public static void main(String[] args) {
  
    StudentGroup stu1 = new StudentGroup();
    stu1.display();
    StudentGroup stu2 = new StudentGroup();
    stu2.display();

  }
}

Output:

default constructor

Parameterized Constructor:

  • The parameterized constructor has parameters.
    • The values for these parameters must be provided when the constructor is called.
  • This type of constructor is used to provide different values for the data members of different objects.
  • The programmer has to explicitly define such a constructor. Java compiler never provides any parameterized constructor, unlike default constructor.
  • Calling the parameterized constructor without defining it will generate a compile-time error.
package mypackage;

public class EmployeeGroup {
  
  String employeename;
  int employeeid;
  double employeesalary;
  
  public EmployeeGroup(String ename, int id, double salary) {
    employeename=ename;
    employeeid=id;
    employeesalary=salary;
    System.out.println("parameterized constructor");	
  }

  void display()
  {
    System.out.println("All the details of the employee are: " + employeename+ ", "+employeeid+", "+employeesalary);
  }
  
  public static void main(String[] args) {
    
    EmployeeGroup emp1 = new EmployeeGroup("Rohan", 999, 30000.00);
    emp1.display();
    
    EmployeeGroup emp2 = new EmployeeGroup("Dev", 76, 68500.00);
    emp2.display();		
  }
}

 

Output:

param constructor

Note:

Whenever you want to create objects with respect to both parameterized constructor and default constructor, it is mandatory to define both the constructors, otherwise it will generate compile time error.

Copy Constructor:

  • Copy constructor is a special technique of the type parameterized constructor.
  • It helps in copying the contents of one object into another object.
  • Separate memory space is allocated for both the objects in this case.
  • Any modification in the first object does not lead to any change in the newly copied object.
package mypackage;

public class Fruit {
  
  String dishname;
  String taste;
  float price;

  Fruit(String const_dishname,String const_taste,float const_price){
    
    dishname=const_dishname;
    taste=const_taste;
    price=const_price;
    System.out.println("parameterized constructor");
  }
  
  public Fruit(Fruit f) {
    //copy constructor. It will copy the values of its argument object
    
    dishname=f.dishname;
    taste=f.taste;
    price=f.price;	
    System.out.println("copy constructor");
  }
  
  void display()
  {
    System.out.println("All the details of the food are: " + dishname+ ", "+taste+", "+price);
  }
  
  public static void main(String[] args) {
    Fruit obj1 = new Fruit("Mango", "sweet",50);
    obj1.display(); 
    Fruit obj2 = new Fruit(obj1); //obj2 will hold same values as of obj1
    obj2.display();		
    
    Fruit obj3 = obj1; //only reference is created pointing to the same area.
    
    System.out.println("copy object directly");
    obj3.display();
    
    System.out.println("\nobj1 values change");
    obj1.dishname ="orange";
    obj1.taste="sour";
    obj1.price=40;
    obj1.display(); 
    
    System.out.println("\nobj2 values do not change");
    obj2.display();	
    
    System.out.println("\nobj3 values change");
    obj3.display();		
  }
}

Output:

copy constructor

As you can see from the above program if you directly assign the object to another object as in

Fruit obj3 = obj1;

it only creates another reference to the same memory space.

Both the objects obj1 and obj3 point to the same memory space. So any modification in the former object obj1 creates a change in the latter object obj3.

But obj2 of the copy constructor remains the same as it is located in a different memory area.

Private Constructor:

  • Constructors can only be private if object creation takes place inside the same class.
    • It cannot instantiate an object outside of that class having that constructor.
  • If you declare a constructor with a private keyword, then it becomes a private constructor.
public class Vehicle {
  
  int vehmodel;
  
  private Vehicle() {
    System.out.println("private constructor");
  }
  
  public static void main(String[] args) {
    Vehicle ob = new Vehicle();
  }
}


public class Car {
  
  int carmodel;
  
  public static void main(String[] args) {
  
    Car ob = new Car();
    Vehicle obj = new Vehicle(); //gives an error as private constructor is called
  }
}

Output:

Creating an object with private constructor inside the same class.

private constructor correct

Creating an object in a different class with the private constructor gives an error.

private constructor error

 

This was all about the types and uses of constructors in Java.

Now that we have become quite familiar with all the parts and characteristics of a Java program, its time for some implementation.

Thus the next section will contain a description of programming level logical structure and implementations of Java. It will include topics on operators, control structure, arrays, and strings.