How to create a parameterized constructor 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.

There are two types of constructors parameterized constructors and no-arg constructors.

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.

Example

public class StudentData {
   private String name;
   private int age;  
   public StudentData(String name, int age){
      this.name = name;
      this.age = age;
   }  
   public StudentData(){
      this(null, 0);
   }  
   public StudentData(String name) {
      this(name, 0);
   }
   public StudentData(int age) {
      this(null, 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 constructor that accepts both values
      System.out.println("Display method of constructor that accepts both values: ");
      new StudentData(name, age).display();
      System.out.println(" ");
     
      //Calling the constructor that accepts name
      System.out.println("Display method of constructor that accepts only name: ");
      new StudentData(name).display();
      System.out.println(" ");
     
      //Calling the constructor that accepts age
      System.out.println("Display method of constructor that accepts only age: ");
      new StudentData(age).display();
      System.out.println(" ");
     
      //Calling the default constructor
      System.out.println("Display method of default constructor: ");
      new StudentData().display();
   }
}

Output

Enter the name of the student:
Krishna
Enter the age of the student:
22

Display method of constructor that accepts both values:
Name of the Student: Krishna
Age of the Student: 22

Display method of constructor that accepts only name:
Name of the Student: Krishna
Age of the Student: 0

Display method of constructor that accepts only age:
Name of the Student: null
Age of the Student: 22
raja
Published on 05-Feb-2021 10:35:01
Advertisements