Page 254 - IT-802_class_12
P. 254

3.12.1 Access Specifier

        There has to be some restriction on the accessibility of the methods as they can also be accessed by other methods, same
        or different class. Hence, access specifiers help a method to be accessed by the objects of the class in different ways.
        So, access specifiers are segregated into three different types which are as follows:

        Ð ÐPublic: The keyword “Public” is used to give access to the methods to any class.
          Example:                public int twice (int i)


        Ð ÐPrivate: The keyword “Private” allows the methods to be accessed only by the same class.
          Example:               private int twice (int i)


        Ð Ð Protected: The keyword “Protected” allows other methods of the same class and the inherited class to access the
           method.

          Example:               protected int twice (int i)

                     Notes



                    When no access specifier is used, then by default it is public.



        3.12.2 Getter and Setter Methods

        Getter and Setter methods are used to secure your code and safeguard your data. Accessors are returned by the getter,
        including values of the data types int, String, double, float, etc. Getter begins with the term “get” and the variable
        name for the benefit of the programme.
        While Setter sets or updates the value (mutators). Any variable that is utilised in a class’s programmes is given a value
        by this. It begins with the phrase “set,” the variable name, and finally. The use of getter and setter functions makes it
        simple for programmers to set and retrieve values for a given data type. The variable’s first letter should be capital in
        both the getter and setter functions.
        package com.mycompany.student;
        class Student{

          private String name;//private variable
          private int rollno;//private variable
            //setter method to set the name
            public void setName(String n) {

             this.name=n;
           }
            //getter method to retrieve the name
            public String getName() {
             return name;

           }
            //setter method to set the roll number
            public void setRollno(int r) {
             this.rollno=r;
          252   Touchpad Information Technology-XII
   249   250   251   252   253   254   255   256   257   258   259