Page 378 - Computer_Science_F5
P. 378

// This code is trying to extend the final class
                 class Main extends FinalClass {  // This will cause a compilation error
                   public void show() {
                     System.out.println(“final method is overridden????.”);
                   }                                                                               Chapter Five: Object oriented programming with Java
          FOR ONLINE READING ONLY
                   public static void main(String[] args) {
                     Main newObj = new Main();
                     newObj.show();
                   }
                 }
                Output:







                                  Figure 5.35: Output for demonstrated final class



                                                       Encapsulation and Java classes
                   Exercise 5.6
                                                       Encapsulation  in  Java  is achieved  by
               1.  Explain the difference between      declaring  class attributes as private
                   public, private, and protected access   and providing public getter  and setter
                   modifiers in Java. Give examples    methods  to access  and  modify  the
                   of when each would be used.         attributes.
               2.  How does the “this” keyword
                   work in Java? Provide examples            Program Example 5.34:
                   to illustrate its usage in different
                   contexts.                             Java program to demonstrate
               3.  Describe the purpose of the “final”   encapsulation
                   keyword in Java. How does it affect
                   variables, methods, and classes?      public class MyClass {
                   Give examples to demonstrate its      public class Car {
                   usage.                                    private String model;

               4.  Can you use the “final” keyword           private int year;
                   with local variables in Java?             // This is Getter method
                   Explain with examples.                    public String getModel() {
               5.  What happens if you try to access a           return model;
                   private member variable of a class        }
                   directly from another class? How          // This is Setter method
                   can you access it using the “this”        public void setModel(String model) {
                   keyword? Provide an example.                  this.model = model;
                                                             }

                                                    369
               Student’s Book  Form Five



     Computer Science Form 5.indd   369                                                     23/07/2024   12:34
   373   374   375   376   377   378   379   380   381   382   383