In the previous post, we learned what is inheritance in Java with its different types and their examples. In this tutorial, we are going to learn what is encapsulation in Java with its 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.
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);
}
}
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());
}
}
No comments:
Post a Comment
Share your thoughts or ask questions below!...👇