Java: Introduction to Encapsulation

Author: Ronald S. Holland
at
Total Application Works




To contact us



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works


    Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <html>
    <head>
    <title>Java: Encapsulation </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/Java/JAV_Encapsulation.html">
    Java Encapsulation </a>
    </table>
    </body>
    </html>
    Source


Table of Contents

Java Resources

Read Me First

The JAV_ENCAP.zip file contains the following files:

  1. CompileandRunMyCar.bat - this file contains the code that when clicked will ompile and run the main program (MyCar.java)
  2. MyCar.java - this file contains the main method code and is the entry point when the program is loaded into memory,
  3. JAV_Encapsulation.html - is the tutorial that describes how to build the Switch program
    • MyCar.java.

Introduction to Encapsulation

This tutorial assumes that you have some prior programming experience. This tutorial is intended to be an introductory discussion on Java and programming. Java as a programming language is widespread and can be found on nearly all computers. This tutorial will prepare you to step through a set of tutorials on Java.

In this particular tutorial we will look into a very useful concept in java i.e. Encapsulation. Encapsulation is one of the four (Abstraction, Encapsulation, Inheritance & Polymorphism) OOPS concepts in Java.

Encapsulation is a practice to bind related functionality (Methods) & Data (Variables) inside a Class with required access modifiers (public, private, default & protected) so that the code can be saved from unauthorized access by outer world and can be made easy to maintain. An example in the real world, is a smart phone. It has many functions that we use without ever knowing what they consist of.

We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters.

If we consider a calculator as an example of encapsulation when:

  1. We enter some data;
  2. Click on a button;
  3. The calculator performs a function;
  4. Then displays the result in the display window.
How the results are calculated is encapsulated. As a user, we never see how it performs its functions.
    
Although a lesser degree of encapsulation can be achieved by making the class members public or protected. In the next section, we will discuss class in more detail.

What is a Class?

The dictionary defines a class as

    a number of people or things grouped together because of certain likenesses or common traits; kind; sort; category
Let's consider the class of automobile, which contains the set of all automobiles. A sampling might be:
  • Acura TL
  • BMW 5 series
  • Buick Century
  • Ford Explorer
  • Honda Pilot
  • Mazda6
  • Toyota Avalon
  • Toyota Highlander
  • Volvo S60
  • etc.
If we were to write one of the examples above in Java, it might look like:

  
class Toyota extends automobile {
   ...
}

class Avalon extends Toyota {
   ...
}
  
Figure 1: automobile inheritance


This example is interpreted as class Avalon is derived from class Toyota and class Toyota is derived from class automobile. When you buy a car, you get an instance of a brand and a model e.g., Toyota Highlander. For example, when we consider the template in Figure 2:, we see a basic example of how a class is configured.

 
public class Encapsulation {
   private int nameData1 ;
   private JButton nameBut1 ; 


   public  Encapsulation() { 
       code ...   
   }

   public  GetData() { 
       code ...   
   }

   public  SetData( int a ) { 
       code ...
   }

   public  static void main(String args[] ) { 
       code ...
   }
}


 
Figure 2: class Template


We will consider encapsulation in more detail in the next section.

What is encapsulation?

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update (for e.g. void setSSN(int ssn))and read (for e.g. int getSSN()) the private data fields then the outside class can access those private data fields via public methods. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better.

 
public class Encapsulation {
    private int ssn;
    private String empName;
    private String empJob;
    private int empAge;

    //Getter and Setter methods
    public int getEmpSSN(){
        return ssn;
    }

    public String getEmpName(){
        return empName;
    }

    public int getEmpAge(){
        return empAge;
    }

    public int getEmpJob(){
        return empJob;
    }

    public void setEmpAge(int newValue){
        empAge = newValue;
    }

    public void setEmpName(String newValue){
        empName = newValue;
    }

    public void setEmpJob(String newValue){
        empJob = newValue;
    }

    public void setEmpSSN(int newValue){
        ssn = newValue;
    }
}
public class EncapsTest{
    public static void main(String args[]){
         Encapsulation obj = new Encapsulation();
         obj.setEmpName("LeBron James");
         obj.setEmpAge(30);
         obj.setEmpSSN(123345678);
         obj.setEmpJob("Singer");
         System.out.println("Employee Name: " + obj.getEmpName());
         System.out.println("Employee SSN: " + obj.getEmpSSN());
         System.out.println("Employee Age: " + obj.getEmpAge());
         System.out.println("Employee Job: " + obj.getEmpJob());
    } 
}
 

Output:

Employee Name: LeBron James
Employee SSN: 123345678
Employee Age: 30
Employee Job: Singer
Figure 3: Inheritance

In above example all the three data members (or data fields) are private which cannot be accessed directly. These fields can be accessed via public methods only. Fields empName, ssn, empAge and empJob are made hidden data fields using encapsulation technique of OOPs.

Advantages of encapsulation:

  1. Makes it easy to model real-world entities – hence easy to understand and maintain
  2. Control the way data is accessed or modified
  3. Makes the class easy to use for clients
  4. Increase reusability
  5. Aids to the flexibility of design e.g. It is possible to add accelerationConfiguration field in the Car. This will enable you to have different acceleration behavior of each car.

Encapsulation is also known as data Hiding.

  1. Objects encapsulate data and implementation details. To the outside world, an object is a black box that exhibits a certain behavior.
  2. The behavior of this object is what which is useful for the external world or other objects.
  3. An object exposes its behavior by means of public methods or functions.
  4. The set of functions an object exposes to other objects or external world acts as the interface of the object.

Example of Encapsulation in Java

Following is another example of

 


import javax.swing.JOptionPane ;
import java.io.*;

/** **************************************************************
 *  The MyCar class shows the steps to drive a car.
 *****************************************************************/
class MyCar {

   String firstNum = "",      // first string entered by user
          secondNum = "",     // second string entered by user
           menu , menu1 ;     // menu display
   double num1,               // first number to add
        num2,                 // second number to add
        num3,                 // second number to add
        sum,                  // sum of num1, num2 and num3
        prod,                 // prod of num1, num3 and number2
        divi,                 // average of num1, num3 and number2
        result ;
   int ret = 0 , Curspd = 0 ;
   boolean notDig , debug = false , usePrevResult = false ;

    /** MyCar constructor - construct the car menu */
   public MyCar() {
      SysPrint("We are in the MyCalc constructor." );

      menu  =         "                                         \n" ;
      menu  = menu  + "    Car Driving Options                  \n" ;
      menu  = menu  + "                                         \n" ;
      menu  = menu  + "  1 - Start engine                       \n" ;
      menu  = menu  + "  2 - Release brake                      \n" ;
      menu  = menu  + "  3 - Put gear into Drive                \n" ;
      menu  = menu  + "  4 - Put gear into Reverse              \n" ;
      menu  = menu  + "  5 - Put gear into Park                 \n" ;
      menu  = menu  + "  6 - Press Brake                        \n" ;
      menu  = menu  + "  7 - Check mirrors for oncoming traffic \n" ;
      menu  = menu  + "  8 - Acclerate to                       \n" ;
      menu  = menu  + "  9 - DeAcclerate to                     \n" ;
      menu1  = menu  ;

      Menu();
   }

   /** **********************************************
    * Method: Menu()
    *
    * Purpose: displays the user options
    * 1 - Start engine                        
    * 2 - Release brake                      
    * 3 - Put gear into Drive                
    * 4 - Put gear into Reverse               
    * 5 - Put gear into Park                  
    * 6 - Press Brake                         
    * 7 - Check mirrors for oncoming traffic  
    * 8 - Acclerate to                        
    * 9 - DeAcclerate to                      
    * 10- Exit     
    *
    *   The logic is:
    *   1 - Show the MyCar menu options
    *   2 - Obtain the menu option chosen by the user
    *   3 - Validate the option number chosen by the user
    *   4 - Check to see if user has chosen to exit
    *       - if not, continue processing
    *   5 - Get the two user entered numbers
    *   6 - Perform the operation the user chose
    *   7 - Determine if the user wants to performed
    *       another operation
    *       - If not, then exit
    *   8 - Determine if the user wants to use the
    *       result of the previous operation
    *
    ************************************************ */
   public void Menu() {
      boolean cont = true , remCont = true ;
      String result2 ;

      String number ;   // first string entered by user

      int number1 ;       // number to process in the list
      int a , b , arr[] = new int[ 250 ] ;

      /** **************************************
       *  
       *****************************************/
loop2:
      while ( cont ) {
         number = "0" ;

         menu  = menu1 ;
         menu  = menu  + "                                         \n" ;
         menu  = menu  + "  10- Exit                               \n" ;
         menu  = menu  + "                                         \n" ;
         menu  = menu  + " Current Speed ........... "  + Curspd + "\n" ;
         menu  = menu  + "                                         \n" ;
         menu  = menu  + " Select one of the option numbers from above     \n" ;

         number =  showIn( menu ,  "MyCar Options " ) ;

         if ( number.equals( "" ) ) {
            number1 =  99  ;
         }
         else {
            if ( checkIfDigit( number ) ) {
               number1 =  Integer.parseInt( number ) ;
            }
            else {
               number1 =  99 ;
            }
         }

         // read in first number from user         
if3:     if ( number1 != 10 ) {

            remCont = getOption() ;
         
            switch ( number1 ) {
               case 1 : //  
                  System.out.println("The The engine has been started " );
               break ;
               case 2 : //  
                  System.out.println("The brake has been released " );
               break ;
               case  3 : //  
                  System.out.println("The car is in drive gear. " );
               break ;
               case  4 : // 
                  System.out.println("The car is in reverse gear. " );
               break ;
               case  5 : //  
                 System.out.println("The car is in Park gear. " );
               break ;
               case  6 : // 
                  System.out.println("The brake has been applied. " );
               break ;
               case  7 : // 
                  System.out.println("I am checking mirrors for oncoming traffic. " );
               break ;
               case  8 : // 
                  System.out.println("The car is accelerating to " +num1 + "/n" );
                  Curspd =  (int)num1 ;
               break ;
               case  9 : //
                  System.out.println("The car is deaccelerating to " +num1 + "/n" ); 
                  Curspd =  (int)num1 ;
               break ;
               case  10 : // ..................... Exit
                  SysPrint("The value of number1 is " + number1 ) ;
                  SysPrint("User chooses to exit."  ) ;
                  cont = false ;
               break ;
               default:
                  JOptionPane.showMessageDialog( null,
                     "The option \"" + number + "\" you selected is not valid.\n" +
                     "Please enter a valid option from above." ,
                     "Invalid Option selected ",
                        JOptionPane.INFORMATION_MESSAGE);
               break ;
            } 
            // .......................................... End of switch construct


            a = (int)JOptionPane.showConfirmDialog(
                   null,
                   "Do you wish to perform another operation? "  ,
                   "Another operation?",
                   JOptionPane.YES_NO_OPTION );

            if ( a == 1 ) {
               cont = false ;
            }
            else {
               a = (int)JOptionPane.showConfirmDialog(
                   null,
                   "Do you wish to use the previous result? \n" +
                   "result =  " + result   ,
                   "Use the previous result?",
                   JOptionPane.YES_NO_OPTION );

               if ( a == 0 ) {
                  num1          = Curspd ;
                  usePrevResult = true ;
               }

               firstNum   = "" ;
               secondNum  = "" ;
               result     = 0.0 ;
            }

         } // .................. End of if3 construct
         else
            cont = false ;
      } // .................. End of while loop

   }


   /** **********************************************
    * Method: getOption()
    *
    * Purpose: display JOptionpane to get user numbers
    *
    *   The logic is:
    *   1 - Use JOptionPane.showInputDialog to get first number
    *     - speed user wants
    *
    ************************************************ */
   public boolean getOption() {
      boolean loopctl = true ;
      boolean loopctl2 = true ;
      int retVal = 0 ;

loop: while ( loopctl ) {
         /** read in first number from user as a string */
         Curspd = getSpeed() ;
         if ( Curspd >= 0 ) {
            convertNumbers() ;  // .............   they are integers            
         }     
            loopctl = false ;  

      }  // .............................  end of while loop

      return loopctl ;
   }

  /** **************************************************
    *  Method: getSpeed()
    *    1- Determine if user wants to use result of 
    *       previous operation
    *    2- Get first number
    *    3- Alert user if first number is null
    *       Goto beginning of loop to get first number
    *       again
    *    4- Ensure number is a digit
    *    5- Alert user if first number is not a digit
    *    6- Break loop if user cancels    *
    *    7- If user has chosen to use previous result, make 
    *       that result the first number
    *       
    ******************************************************/
   public int  getSpeed() {

      boolean loopctl = true ;
      boolean loopctl2 = true ;
      int retVal  = 0 ;

      if ( !usePrevResult ) {
            System.out.println( "The Previous Result is " + usePrevResult  + "\n") ;

loop2:   while( loopctl2 ) {
            firstNum =
                  JOptionPane.showInputDialog( "Enter final speed. Curent speed is " + Curspd );

            if( firstNum.equals( "" ) ) {
               JOptionPane.showMessageDialog(  null, "Null values are not allowed. " +
                     "Please enter a number" ,
                     "No Null Values" ,
                     JOptionPane.ERROR_MESSAGE ) ;
               continue loop2 ;
            }
            System.out.println( "The speed is " + firstNum  + "\n") ;

            if ( !checkIfDigit( firstNum ) ) {
               ret = JOptionPane.showConfirmDialog(  null,
                       "The firstNum '" +  firstNum + "' is not a number. " +
                       "Do you wish to continue?" ,
                       "" + firstNum + " is not a number" ,
                       JOptionPane.YES_NO_OPTION ) ;
               SysPrint("The value of ret is " + ret );
               if ( ret == 1 ) {  // ..............................check for cancel
                  loopctl = false ;  // ........................... use wants to cancel
                  break loop2 ;
               }
               else {
                  loopctl2 = true ;
                  continue loop2 ;
               }
            }  // .............................  end of first number check
            else if ( loopctl ==  true ) {
               loopctl2 = false ;
               break loop2  ;
            }
         }  // ................. end of loop2
      }  
      else {    // ................. use previous result
         firstNum = "" + (int)num1 ; 
         result   = 0.0 ; 
         usePrevResult   = false ; 
         loopctl2 = false ;
      }  

      return retVal ;
   }


   /** **************************************************
    *  Method: checkDigit( String strVal )
    *    1- Make sure that the data entered is a digit
    *       - check each character to ensure it is a digit
    ******************************************************/
   public boolean  checkIfDigit( String strVal ) {

       int strLength = 0;
       boolean notDig2 = true;

       strLength = strVal.length();  //...... number of digits entered

       for (int ii = 0; ii < strLength; ii++) { //...... loop on number of digits entered
          if (!Character.isDigit(strVal.charAt(ii)) ) {
             notDig2 = false;
             notDig  = false;
             break;
          }
       }

       return notDig2;
   }

   /** **************************************************
    *  Method: convertNumbers()
    *    1- Converts string data to type double.
    *
    ******************************************************/
   public void convertNumbers() {
      /** convert numbers from type String to type int */
      num1 = Double.parseDouble( firstNum );
   }

   /** **************************************************
    *  Method: convertNumbers()
    *    1- Converts string data to type double.
    *
    ******************************************************/
   public void SysPrint( String str ) {
      if ( debug ) {
         System.out.println("" + str );
      }
   }

   /** ***********************************************
    *  Method: showIn( String mess , String title )
    *    1- The purpose of this method is to display the
    *       menu using a JOptionPane - show calculator options.
    *
    **************************************************/
   public String showIn( String mess , String title ) {
      String ret  ;

      ret = JOptionPane.showInputDialog( null ,
                   mess ,
                   title ,
                   JOptionPane.PLAIN_MESSAGE ) ;

      return ret ;
   }

   /** ***********************************************
    *  Method: main( String args[] )
    *    1- The purpose of this method is to serve as a
    *       entry point when the application is loaded
    *       by Java.
    *    2- Creates an instance MyCalc class.
    *
    **************************************************/
   public static void main( String args[] ) {

      MyCar app = new MyCar() ; /** creates an instance of MyApp  */



      System.exit( 0 );   /** end the program */
   }
}

 
Figure 4: Inheritance

Definitions

class

    the basic building block of an object-oriented language such as Java--is a template that describes the data and behavior associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class.

Object-oriented programming

    A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs to control the behavior of a machine or to express algorithms.(OOP) is a programming paradigm that uses "objects" data structures consisting of data fields and methods together with their interactions to design applications and computer programs.

programming language -

    Programming Language A vocabulary and set of grammatical rules for instructing a computer to perform specific tasks. The term programming language usually refers to high-level languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal.

template

    template (n.) (1) Something that establishes or serves as a pattern for reference. (2) A plastic or paper diagram that you can put on your keyboard to indicate the meanings of different keys for a particular program.









HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works