Data Hiding Getter & Setter in Java


This Java program demonstrates the usage of getter and setter methods to set and retrieve the length and width of a rectangle, and to calculate its area. The program defines a class ShapeRectangle with private instance variables length and width, and getter and setter methods to access and modify these variables.

The getLength and getWidth methods are used to retrieve the values of length and width instance variables, respectively. The setLength and setWidth methods are used to set the values of length and width instance variables, respectively. These methods also perform validation to ensure that the length and width values are positive. The area method calculates the area of a rectangle using the length and width instance variables and returns the result.

In the main method, an instance of the ShapeRectangle class is created using the new operator. The setLength and setWidth methods are called with the arguments -10 and 20, respectively. Since the setLength method has a validation check to ensure that the length value is positive, it sets the length to 0. The getLength, getWidth, and area methods are then called on the object to retrieve the values and calculate the area of the rectangle.

Source Code

//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() {
        int a = length * width;
        return a;
    }
}
 
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());
    }
}
 

Output

Area of Rectangle : 200
Area of Rectangle : 600
To download raw file Click Here

Basic Programs