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

COMPUTER SOFTWARE APPLICATION - CITS





                  Student(String name, int age) {
                      this.name = name;

                      this.age = age;
                  }
                  // Method to display student details
                  void displayDetails() {
                      System.out.println(“Employee Details “ );
                      System.out.println(“-----------------” );

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

              public class Student_Demo {
                  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();
                  }
              }
           Output:



















           Explanation:
           •  In this example, we have a class MyClass with three constructors.
           •  The first constructor calls the second constructor using this(0, 0), which initializes x and y to 0.
           •  The second constructor calls the third constructor using this(x, y, “Default”), which initializes x, y, and name.
           •  The third constructor initializes all the attributes x, y, and name based on the provided arguments.

           •  In the main method, we create an instance of MyClass using the first constructor, which in turn triggers the
              chain of constructors.
           •  The display method is called to print the object’s attributes.







                                                           116

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