Use Of Constructor In Java

Use Of Constructor In Java

Constructor in Java

Here, on this page, we will discuss about the uses of constructor in java programming and why do we need Java Constructors,

A Java constructor is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

Need of Constructor:

Constructors in java is as similar to methods in Java. It invokes automatically at the time of initialization or the object creation. It has the same name as of class name. It is called when an instance of the class is created. we don’t need to call it manually or we can say that the constructor is the method that can be invoked using the new operator at the time of object creation.

There are different reasons to use constructor that can be:

  • The main use of Constructor is to initialize the data fields of objects in the class. You can also initialize your required data sets with the help of parametrized constructor.
  • Constructor doesn’t have any return type, if it contains a return type it’ll be treated as methods by the compiler or JVM machine which makes them different from the class methods and helps to initialize the values accordingly.
  • If we don’t want to initialize the values of the data fields of a class thenthere are some values which will be assigned automatically to the data fields at the time of object creation that are :
    • All boolean data fields will be set as false.
    • All integer data fields will be set as 0.
    • All String data fields will be set as null.

Example:

Run
import java.util.*;

// defining the student class
class Student {
  int id;
  String name;

  // Constructor
  Student(int i, String n) {
    id = i;
    name = n;
  }

  // defining the Method
  void display() {
    System.out.println(id + " " + name);
  }
}

class Main {
  public static void main(String[] args) {
    // Creating objects and passing values
    Student s1 = new Student(101, "John");
    Student s2 = new Student(102, "Jane");

    // Calling display method
    s1.display();
    s2.display();
  }
}
Output:

101 John
102 Jane

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription