Saturday, April 8, 2017

Encapsulation

Encapsulation in Java is the mechanism of wrapping data (variables) and code acting on data (methods) together as a single unit. The implementation details are hidden from outside classes and it can be accessed via public methods of setter and getter defined by class. Outside classes are unable to access private data members (variables and methods) directly and it is so called data hiding.

Advantages: improved flexibility, reusability and maintainability. Whenever there is changes in method behavior we only need to change the method instead of relevant outside classes.

To achieve encapsulation in Java:
-Declare the variables of a class as private.
-Provide public setter and getter methods to modify and view the variables values.

class Vehicle
{
  private int speed;
  private String color;
  
  public void setSpeed(int s)
  { speed = s; }
  
  public void setColor(String c)
  { color = c; }
  
  public int getSpeed()
  {return speed;}
  
  public String getColor()
  {return color;}
}

public class VehicleTest
{
  public static void main(String args[])
  {
Vehicle v = new Vehicle();
v.setColor("blue");
v.setSpeed(300);
  System.out.println("Speed: "+v.getSpeed());
System.out.println("Color: "+v.getColor());
  }
}

Result:
Speed: 300
Color: blue

No comments:

Post a Comment

Abstraction vs Interface

Abstract Interface method abstract and concrete abstract only, support default and static method ...