What is the use of parametrized constructor in Java?



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.

There are two types of constructors parameterized constructors and no-arg constructors a parameterized constructor accepts parameters.

The main purpose of a constructor is to initialize the instance variables of a class. Using a parameterized constructor, you can initialize the instance variables dynamically with the values specified at the time of instantiation.

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

Example

In the following example the Student class has two private variables age and, name. From main method we are instantiating the class variables using parameterized constructors −

Live Demo

import java.util.Scanner; public class StudentData {    private String name;    private int age;    //parameterized constructor    public StudentData(String name, int age){       this.name =name;       this.age = age;    }      public void display(){       System.out.println("Name of the Student: "+this.name );       System.out.println("Age of the Student: "+this.age );    }    public static void main(String args[]) {       //Reading values from user       Scanner sc = new Scanner(System.in);             System.out.println("Enter the name of the student: ");       String name = sc.nextLine();             System.out.println("Enter the age of the student: ");       int age = sc.nextInt();             System.out.println(" ");             //Calling the parameterized constructor       new StudentData(name, age).display();    } }

Output

Enter the name of the student: Sundar Enter the age of the student: 20 Name of the Student: Sundar Age of the Student: 20
Updated on: 2021-02-05T10:31:10+05:30

509 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements