Page 223 - Scholarly Works of Faculty
P. 223

CAVITE STATE UNIVERSITY
                               T3 CAMPUS
                               Department of Information Technology          COSC 65 – Programming Languages

               Simple example of Encapsulation in Java
                       Let’s see the simple example of encapsulation that has only one field with its setter
               and getter methods.

                  // A Java class which is a fully encapsulated class.
                  // It has a private data member and getter and setter methods.

                  class Student {
                      private String Name;
                          public String getName(){
                              return Name;
                          }
                          public void setName(String name){
                              Name = name;
                          }
                  }
                  public class JavaApplication1 {
                      public static void main(String[] args) {


                        Student Student1 = new Student(); // creating the object of the class Student
                        Student1.setName("Christian");  // setting name as ‘Christian’ using method setName()
                        System.out.println(Student1.getName());   // calling the method getName()
                      }
                  }

                  // A Java class which has only getter method / THIS IS A READ-ONLY CLASS
                  class Student {
                        private String college = “DIT”;

                        public String getCollege() {
                        return college;
                  }
                  }
                  // Now, you can’t change the value of the college data member which is “DIT”.


                  // A Java class which has only getter method / THIS IS A READ-ONLY CLASS
                  class Student {
                        private String college = “DIT”;

                        public String getCollege() {
                        return college;
                  }
                  }
                  // Now, you can’t change the value of the college data member which is “DIT”.


                  // A Java class which has only setter method / THIS IS A WRITE-ONL CLASS
                  class Student {
                        private String College;
                               public void setCollege(String college) {
                                       College = college;
                               }
                  }  // now you can’t get the value of the college, you can only change the value of college data
                 member

                                                                                                 Page | 82
   218   219   220   221   222   223   224   225   226   227   228