Java Encapsulation

 Encapsulation

It is the process of hiding the data from the world. 

To achieve this we can use:

  • Declare class variables/attributes as private
  • Provide public get and set methods to access and update the value of a private variable.

Benefits

  • ·      Better control of class attributes and method
  •        Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • ·       Flexible: the programmer can change one part of the code without affecting other parts
  • ·       Increased security of data.
  •       Example 01:.

        //Data Hiding Getter and Setter in Java

class ShapeRectangle {

private int length, width;

//Getter Method

int getLength() {

return length;

}

int getWidth() {

return width;

}

//Setter Method

void setLength(int l) {

if (l > 0)

length = l;

else

length = 0;

}

void setWidth(int w) {

if (w > 0)

width = w;

else

width = 0;

}

int area() {

return length * width;

}

}

public class get_set {

public static void main(String args[]) {

ShapeRectangle o = new ShapeRectangle();

o.setLength(10);

o.setWidth(20);

System.out.println("Length : " + o.getLength());

System.out.println("Width : " + o.getWidth());

System.out.println("Area of Rectangle : " + o.area());

}

}

Post a Comment

0 Comments