Page 130 - CTS - CSA TP - Volume 2
P. 130

COMPUTER SOFTWARE APPLICATION - CITS




                  // Parameterized constructor
                  Student(String name, int age) {

                      this.name = name;
                      this.age = age;
                  }
                  // Method to display student details

                  void displayDetails() {
                      System.out.println(“Name: “ + name);
                      System.out.println(“Age: “ + age);
                  }
              }

              public class StudentDemo {
                  public static void main(String[] args) {
                      // Creating an instance of Student using the parameterized constructor
                      Student student = new Student(“John”, 20);

                      // Displaying student details
                      student.displayDetails();
                  }
              }


           Explanation:

           •  In this program, we define a class Student with attributes name and age.
           •  We provide a parameterized constructor for the Student class, which initializes the name and age attributes
              with the values passed as parameters.

           •  In the main method, we create an instance of the Student class using the parameterized constructor, passing
              specific values for the name and age.
           •  We call the displayDetails method of the Student class to display the student details.

           Parameterized  constructors  allow  you  to  initialize  object  attributes  with  specific  values  at  the  time  of  object
           creation. They provide flexibility and convenience in setting initial state for objects, making them ready for use.



           3  Constructor chaining in Java
              Constructor chaining in Java refers to the process of calling one constructor from another constructor within
              the same class or from the constructor of the superclass. Here are examples of constructor chaining with
              explanations:
           TASK 1: Constructor Chaining within the Same Class

              class Student {
                  String name;
                  int age;
                  // Parameterized constructor






                                                           115
                                CITS : IT & ITES - Computer Software Application - Exercise 97
   125   126   127   128   129   130   131   132   133   134   135