What are parametrized constructors in Java?

JavaServer Side ProgrammingProgramming

A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.

Parameterized constructors

A parameterized constructor accepts parameters with which you can initialize the instance variables. Using parameterized constructor, you can initialize the class variables dynamically at the time of instantiating the class with distinct values.

Syntax

public class Sample{
   Int i;
   public sample(int i){
      this.i = i;
   }
}

Example

Live Demo

public class Test {
   String val;
   Test(String val){
      this.val = val;
   }
   public static void main(String args[]){  
      Test obj = new Test("test");
      System.out.println(obj.val);
   }
}

Output

test

Example

Live Demo

import java.util.Scanner;
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);
      System.out.println(obj.num);
      System.out.println(obj.data);
      System.out.println(obj.flt);

   }
}

Output

Enter an integer value:
1024
Enter a string value:
test
Enter a floating point value:
11.2
1024
test
11.2
raja
Published on 05-Feb-2021 10:34:14
Advertisements