Page 379 - Computer_Science_F5
P. 379

Computer Science      // This is Getter method  it can be accessed if you provide the
                                                     public  “get”  and  “set”  methods. In
                 public int getYear() {
                                                     this case, the  get  method is used to
                     return year;
                                                     return the value of the variable while
                 }
                                                     the set method is used to set the value,
          FOR ONLINE READING ONLY
                 // This is Setter method
                 public void setYear(int year) {     as shown in Program Example 5.38.
                     this.year = year;               Getter and Setter syntax: They start with
                 }                                   get  or  set,  followed  by  variable  name.
             }                                       The  first  letter  of  the  variable  name
                                                     should be written in upper case.
           Getter  and setter  methods:  Getter
           methods are responsible for fetching         Activity 5.11:
           the values of private attributes, whereas
           setter  methods are  used to  modify       Visualisation of encapsulation in
           the  attribute  values.  These methods     Java
           facilitate  controlled  access to class    Use Jeliot  3 or later version,
           data  and  uphold  the  principle  of data   visualise  the  step  by step execution
           encapsulation.  As  explained  above,      of java program  to explore  about
           that  private  variables  can  only  be    encapsulation in Java. Use the code in
           accessed  within  the  same  class  (an    Program Example 5.37.
           outside class cannot access it). However,



                   Program Example 5.35:

            Java program to demonstrate get and set methods

               public class Animal {
                 private String name; // This shows restricted access

                 // Getter
                 public String getName() {
                   return name;
                 }


                 // Setter
                 public void setName(String newName) {
                   this.name = newName;
                 }
               }



                                                 370
                                                                for Advanced Secondary Schools



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