Page 360 - Computer_Science_F5
P. 360

Program Example 5.21:

                Java program to create a class with default constructor

                  // This code shows a parameterized constructor                                   Chapter Five: Object oriented programming with Java
                 class MyClass {
          FOR ONLINE READING ONLY
                     int x;
                     MyClass(int I) { // The constructor here has a parameter
                         x = I;
                     }
                 }
                 class ConstraDemo {
                     public static void main(String args[]) {
                         MyClass t1 = new MyClass(10);
                         MyClass t2 = new MyClass(88);
                         System.out.println(t1.x + “ “ + t2.x);
                     }
                 }


                Output:




                                      Figure 5.20: Output of Java class print

              In this version of the program, the MyClass  (e) Constructor overloading
              ( ) constructor defines one parameter  Constructor overloading refers to creating
              called I, which is used to initialise the  multiple constructors in a class with
              instatnce variable, x. Thus, when the    different parameter lists. This enables
              line MyClass t1 =new MyClass (10) ;      the creation of objects with different
              executes, the value 10 is passed to I, which   argument combinations, offering
              is then assigned to x.                   flexibility in initialising objects to suit


              The choice of constructor relies on you   various scenarios. In Java, constructor
              as a programmer depending on specific    overloading is  similar  to  method
              requirements. If you prefer objects to always   overloading. In method overloading,
              have default values, a default constructor   various method definitions are generated
              could be adequate. Nevertheless, if you   according to different parameters.
              require greater control over initialisation or   Through constructor overloading, you
              the flexibility to create objects with varying   can achieve diverse approaches to object
              initial states, parameterised constructors   initialisation, accommodating varying
              become necessary.                        numbers of parameters.  Following is a

                                                    351
               Student’s Book  Form Five



     Computer Science Form 5.indd   351                                                     23/07/2024   12:34
   355   356   357   358   359   360   361   362   363   364   365