Constructors in Java with examples

Constructors are a fundamental concept in the Object-Oriented Programming (OOP) paradigm of Java, enabling developers to initialize objects with default or custom values. In this article, we will examine the fundamentals of Java constructors.

When an object is created in Java, a constructor is a unique method that is called. It can also be used to allocate resources, set default values, and call other methods in addition to initializing the object's instance variables.

Constructors in Java do not have a return type, not even void, and they share the same name as the class in which they are defined.

The general form of a constructor in Java is as follows:

// Class definition
public class ClassName {
   // Fields or attributes
   private int attribute1;       // To ensure encapsulation, make the attribute private
   private String attribute2;
   private double attribute3;

   // Constructor
   public ClassName(int attribute1, String attribute2, double attribute3) {
      this.attribute1 = attribute1;
      this.attribute2 = attribute2;
      this.attribute3 = attribute3;
   }

   // Method
   public void methodName() {
      // block of code to define this method
   }

   // More methods
}

For example:

public class ConstructorExample {
   public static void main(String[] args) {
      Student studObj = new Student(345, "Edwin Chadwick", 3.5);

      System.out.println("----Student information----");
      studObj.printInfo();

      studObj.updateGpa(4.0);

      System.out.println("\n----Student's updated information----");
      studObj.printInfo();
   }
}

class Student {
   private int id;
   private String name;
   private double gpa;

   // Constructor
   public Student(int id, String name, double gpa) {
      this.id = id;
      this.name = name;
      this.gpa = gpa;
   }

   public void printInfo() {
      System.out.println("Student ID: " + id);
      System.out.println("Name: " + name);
      System.out.println("GPA: " + gpa);
   }

   public void updateGpa(double newGpa) {
      this.gpa = newGpa;
   }
}

The output of this Java example is shown in the screenshot below:

java constructor example

The constructor for the "Student" class in this example takes the values "id," "name," and "gpa" as its arguments, and uses them to set the respective private fields. Using the "new" operator and the necessary constructor arguments, a "Student" class object is created in the main() method. The printInfo() method is called on the "studObj" after the object is created to display the student's information. The student's GPA is then updated by calling the updateGpa() method. Finally, the updated information is displayed by calling the printInfo() method once more.

Therefore, the use of a constructor makes it simple to create "Student" objects with the necessary fields initialized. The constructor initializes the fields with the arguments passed in, and the printInfo() and updateGpa() methods can be used to manipulate the data.

Types of constructors in Java

There are four types of constructors available in the Java programming language, which are

Default Constructor in Java

In Java, a default constructor is one that is generated by the Java compiler when a class does not explicitly define any constructor. The default constructor takes no arguments and simply sets the default values for all fields in the class. When a class object is created using the "new" keyword without any arguments, the default constructor is called. As an example:

Java Code
public class DefaultConstructorExample {
    private String name;
    
    // Default constructor
    public DefaultConstructorExample() {
        name = "default";
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public static void main(String[] args) {
        DefaultConstructorExample obj = new DefaultConstructorExample();
        
        // Print the initial value of the object's field
        System.out.println("Initial value:");
        System.out.println("Name: " + obj.getName());
        
        // Update the value using the setter method
        obj.setName("Edwin");
        
        // Print the updated value
        System.out.println("\nUpdated value:");
        System.out.println("Name: " + obj.getName());
    }
}
Output
Initial value:
Name: default

Updated value:
Name: Edwin

No-Argument Constructor in Java

A no-argument constructor is a constructor that accepts no arguments and initializes fields with predefined values. The no-argument constructor, unlike the default constructor, is explicitly defined in the class. For example:

public class XYZ {
   private String name;

   // No-argument Constructor
   public XYZ() {
      name = "Edwin";
   }
}

In contrast to a default constructor, which is generated by the compiler in the absence of any other constructor definitions for the class, a no-argument constructor simply takes no arguments.

Copy Constructor in Java

A copy constructor creates a new object with the same values as an existing object. It takes an object of the same class as a parameter and populates its fields with the values of the passed object's fields. For example:

public class XYZ {
   private int id;
   private String name;

   // Copy Constructor
   public XYZ(XYZ emp) {
      this.id = emp.id;
      this.name = emp.name;
   }
}

Parameterized Constructor in Java

A parameterized constructor is one that accepts one or more arguments and initializes the fields with the specified values. This type of constructor permits the user to specify the field values during object creation. For example:

public class XYZ {
   private int id;
   private String name;

   // Parameterized Constructor
   public XYZ(int id, String name) {
      this.id = id;
      this.name = name;
   }
}

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!