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

COMPUTER SOFTWARE APPLICATION - CITS




              }
              public class Employee_Demo {
                  public static void main(String[] args) {

                      // Creating an instance of Employee using the parameterized constructor
                      Employee employee = new Employee(“John”, 50000);


                      // Displaying employee details

                      employee.displayDetails();
                  }
              }


           Output:


















           Explanation:
           •  In this program, we define a class Employee with attributes name and salary.

           •  We provide a parameterized constructor for the Employee class, which initializes the name and salary attributes
              with the values passed as arguments.
           •  In the main method, we create an instance of the Employee class using the parameterized constructor, passing
              values for the name and salary.
           •  We call the displayDetails method of the Employee class to display the employee details.
           These examples demonstrate the use of different types of constructors in Java. Constructors are used to initialize
           the state of objects during their creation. Default constructors initialize  the attributes to default values, while
           parameterized  constructors  allow  us  to  initialize  the  attributes  with  specific  values.  Understanding  and  using
           constructors effectively is essential for object-oriented programming in Java.


           TASK 2: Parameterized Constructor in a Rectangle Class

              // Area of a rectangle using Parameterized Constructor
              class Rectangle {
                  double length;
                  double width;
                  // Parameterized constructor

                  Rectangle(double length, double width) {
                      this.length = length;




                                                           113
                                CITS : IT & ITES - Computer Software Application - Exercise 97
   123   124   125   126   127   128   129   130   131   132   133