What Are Constructors In Java?

In this tutorial, we are going to learn What are constructors in java? As constructors are functions which the same name as the class which does not require to class by any object, Where it calls itself explicitly as the object of that class is created.

What Are Constructors In Java?

Constructors in java are special functions that have the same name as of name of that particular class. It has some special properties like it can call itself explicitly just by creating the objects of that class.

Constructors In Java

Types Of Constructors

There are two types of constructors and let us learn about them.

Non-parameterized Or Default Constructors

It is a constructor which does not have any parameters as arguments or we can say simply the constructor or empty constructor. It is a special constructor which gets called explicitly while creating the object of that class

Let’s take an example of the same

public class Test {
   int num;
   String data;
   float flt;
   Test(){
      this.num = 100;
      this.data = "test";
      this.flt = 125.33f;
   }
   public static void main(String args[]){  
      Test obj = new Test();
   }
}

Here we can say how the class test is a class that has a default constructor as a test and as soon as we create the object of the class the constructor is called.

Parameterized Constructor

they are the constructors which have certain parameters or arguments passed. To call such a constructor we have to pass the arguments while creating the objects of a class, It does not call until the parameters do not match with arguments present in the constructors.

For more information, lets follow the example

public class Test {
   int num;
   String data;
   float flt;
   Test(int num, String data, float flt){
      this.num = num;
      this.data = data;
      this.flt = flt;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int num = sc.nextInt();
      System.out.println("Enter a string value: ");
      String data = sc.next();
      System.out.println("Enter a floating point value: ");
      float flt = sc.nextFloat();      
      Test obj = new Test(num, data, flt);

   }
}

As we can see the constructor has three parameters so during the creating objects we need to pass three arguments only then we can call the test constructor in example, we have done the same

 

Learn More about constructors in Java at: Constructors In java

And also visit at JAVA TUTORIALTo learn more about java and solve your doubts regarding java.

Leave a Comment

%d bloggers like this: