Data Hiding Getter & Setter in Java


A class is a non-primitive or user-defined data type in Java, while an object is an instance of a class. They are getters and setters; the standard way to provide access to data in Java classes. Setters and Getters allow for an object to contain private variables which can be accessed and changed with restrictions.

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