• Breaking News

    Wednesday, 4 November 2015

    Encapsulation In Java



    Hi Guys in this tutorial we will discuss about Encapsulation.

    Basically Encapsulation is the basic principal of object programming language.

    1. Encapsulation is used to bind data and operation apply on that data into single unit, Encapsulation  hide data from the outside world.

    2.   In term of programming language Encapsulation is a class that contain private variable  i.e. is data and method that operate on data, we cannot access data directly so to access data class contain getter and setter of each variable to read and write data respectively. 

    3.  Encapsulation hide data within a object.

    4.  Java Bean is best example of encapsulation which contain private variable and getter and setter of that variable.

    Now Consider one simple example related to Encapsulation.

    Suppose we have class Car which have property 

    1. Model

    2. Color

    So Model and color is our Car data i.e  private variable of our class so we cannot access that outside of  class ,so to access that data we have created getter and setter of that data.


    package com.kodemaker;
    
    public class Car {
       
        private String model;
        private String color;
     
        public String getModel() {
           return model;
        }
        public void setModel(String model) {
           this.model = model;
        }
        public String getColor() {
           return color;
        }
        public void setColor(String color) {
          this.color = color;
        } 
    }
    

    Below is another class which cannot directly access car model and color. so this class used getter and setter of model and color.

    package com.kodemaker;
    
    public class EncapsulationTest {
     
       public static void main(String[] args) {
        
           Car c = new Car();
      
           //not write private variable so use setter of that 
           //c.model = 'Test Model'
      
           c.setModel("Test Model");
           c.setColor("Test Color");
      
           //not read  private variable so use getter of that 
           //System.out.println('Access using getter '+c.model);
      
           System.out.println("Access using getter "+c.getModel());
           System.out.println("Access using getter "+c.getColor());
      
       }
    }
    

    Output of above programme


    Access using getter Test Model
    Access using getter Test Color
    

    No comments:

    Post a Comment