Page 376 - Computer_Science_F5
P. 376

(e) Final keyword
              In the Java programming language, the “final” keyword is employed to indicate
              constants. It can be applied to variables, methods, and classes. When any of these
              entities is declared as final, it can only be assigned a value once. This means that a  Chapter Five: Object oriented programming with Java
              final variable cannot be reassigned with a different value. In this case, also a final
          FOR ONLINE READING ONLY
              method cannot be overridden by a subclass. As for variable and method, a final class
              cannot be extended by another class.


              (i) Final variable
              In Java the value of a final variable cannot be changed, as shown in Program
              Example 5.31.

                   Program Exampe 5.31:

               Java program demonstrating final variable of a final keyword

                   class MyClass {
                     public static void main(String[] args) {
                       //this code show a final variable
                       final int age = 93;


                       // this code want to change the final variable
                       age = 39;
                       System.out.println(“Age: “ + age);
                     }
                   }

                Output:








                                    Figure 5.33: Output "final" keyword program


               (ii) Final method
              Program Example 5.32 demonstrate how the final method cannot be overridden. In
              this case, the final method in parent class cannot be overridden by a child class. In
              this example, a final method named show() is created inside the class FinalClass.
              The Main class inherits the 'FinalClass' class. When you try to override the final
              method in the Main class you might end up with compilation error.


                                                    367
               Student’s Book  Form Five



     Computer Science Form 5.indd   367                                                     23/07/2024   12:34
   371   372   373   374   375   376   377   378   379   380   381