Page 358 - Computer_Science_F5
P. 358

Program Example 5.18:

               Java program to create a constructor

                 // This create a Application class                                                Chapter Five: Object oriented programming with Java
                 public class Application {
          FOR ONLINE READING ONLY
                   int x;  // This declares a class attribute
                   // Create a class constructor for the Application class, with method declared the same //
                 name as a class
                   public Application() {
                     x = 118;  // Set the initial value for the class attribute x
                   }
                   public static void main(String[] args) {
                     Application myApp = new Application(); // Create an object of class Application (This
                                                                                      //will call the constructor)
                     System.out.println(myObj.x); // Print the value of x
                   }
                 }


              Observe Program  Example 5.19 that  is declared  with string and is set to  print
              information of an object with string value of an attribute.

                      Program Example 5.19:


               Java program to create a constructor

                 public class Car {
                    private String brand;
                    private String model;
                        // Constructor with parameters
                    public Car(String brandName, String CarModel) {
                        this. brandName = brandName;
                        this. CarModel = CarModel;
                    }
                        public void carDetails() {
                        System.out.println(“Brand Name: “ + brandName);
                        System.out.println(“Car Model: “ + CarModel);
                    }
                        public static void main(String[] args) {
                        // Creating an object using the constructor
                        Car schoolCar = new Car(“Nissan”, “X-Trail”);
                                // Calling a method to display car information
                        schoolCar.carDetails();
                    }
                }


                                                    349
               Student’s Book  Form Five



     Computer Science Form 5.indd   349                                                     23/07/2024   12:34
   353   354   355   356   357   358   359   360   361   362   363