Data Encapsulation in Java

Data Encapsulation in Java

Data Encapsulation in Java

In this article am going to explain the most important topic in Java object-oriented programming, data encapsulation.

What is Data Encapsulation?

Data encapsulation is simply declaring the data fields private. This protects the data fields/ variables values from direct access outside the class.

How is Data Accessed and Changed?

The data can be accessed and changed by getter and setter methods, which the programmer has to provide for each data field. A getter method returns the value of the private data field while a setter method modifies the private data field’s value. For this reason, getter and setter methods are also known as accessors and modifiers.

Here is the general structure of a getter method:

public returnType getVariableName()

Here is the general structure of a setter method.

public void setVariableName(dataType variableName)

Why Should You Make Data Fields Private

Declaring data fields private is important because:

  1. The class is less vulnerable to bugs and easy to maintain. Why? Because the data is not modified directly and the setter method can be set to only accept nonarbitrary values.

  2. Prevents tampering of data by mistake.

How Can You Do This

I have provided an example of a Java class of a Rectangle object with private data fields.


public class Rectangle{

private double width ;

private double length ;

public static int numberOfObjects;

public Rectangle(){

numberOfObjects ++;

}

public Rectangle(double newWidth, double newLength){

width = newWidth;

length = newLength;

numberOfObjects ++;

}

public double getWidth() {

return width;

}

public double getLength() {

return length;

}

public void setWidth(double newWidth) {

width = (newWidth <=0) ? newWidth : 0; //if the width is less than zero then width is set to be zero because width or length can not be a negative number

}

public void setLength(double newLength) {

length = (newLength <=0) ? newLength: 0;

}  
public double getArea(){

return width * length;

}

public double getPerimeter(){

return 2 * (width + length);

}

public static void main(String[] args) throws Exception {

Rectangle rect = new Rectangle(2,5);

System.out.println("perimeter is " + rect.getPerimeter() + " and area is " + rect.getArea());

System.out.println("number of objects created is " + numberOfObjects);

}

}

Final Words

Using data field encapsulation will make your code clean and secure and make you stand out in a world of many programmers.