Encapsulation In Java With Examples

Encapsulation in java means binding data and code together into a single unit.

In simple words Encapsulation is like putting things inside a box and controlling who can access them. In Java, we use classes to create these boxes. Each box (class) has some data (variables) and actions (methods) that can be performed on that data.

Encapsulation in Java, Java Encapsulation example

In Java, encapsulation means putting data inside a class and making it private. This way, other classes can't directly access that data. To access that data from outside the class, we use public methods called getters and setters. Getters let other classes get the values of the private data, and setters allow them to change the data.

Encapsulation Example 1:

//Code in AreaOfRectangle class
public class AreaOfRectangle {

	private int length;
	private int width;
	
	public AreaOfRectangle(int length, int width) {
		this.length = length;
		this.width = width;
	}
	
	public int getArea() {
		return length*width;
	}
    
}

//Code in Main class
public class Main {

	public static void main(String[] args) {
		AreaOfRectangle rectangle = new AreaOfRectangle(5, 8);
		int area = rectangle.getArea();
		System.out.println("Area Of rectangle is: "+area);
	}

}


OUTPUT:

Area of rectangle is: 40


In the code above, encapsulation is achieved by declaring the instance variables 'length' and 'width' as private, which restricts direct access to these variables from outside the class. The public constructor 'AreaOfRectangle(int length, int width)' allows external code to create instances of the class and initialize the private instance variables. The public method 'getArea()' provides a controlled interface to retrieve the calculated area of the rectangle based on the private instance variables. However, there are no corresponding setter methods to modify the values of 'length' and 'width,' which limits encapsulation to data retrieval only.

Here is an example of encapsulation using setter and getter methods.


Encapsulation Example 2:

//Code in Students class
public class Students {

	private String name;
	private int age;
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	public int getAge() {
		return age;
	}
}

//Code in Main class
public class Main {

	public static void main(String[] args) {
		Students students = new Students();
		students.setName("Ravi");
		students.setAge(22);
		System.out.println("Student Name is "+students.getName()+" & Age is "+students.getAge());
	}

}


OUTPUT:

Student Name is Ravi & Age is 22


    Related Topics:




No comments:

Post a Comment

If you have any doubts, please discuss here...👇