OOP IN JAVA - [ ENCAPSULATION & this KEYWORD]
ENCAPSULATION
Encapsulation is one of the last fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
In Java, encapsulation is the technique of combining code and data into a single entity.
Java allows us to entirely encapsulate a class by keeping all of its data members private. We can now set and retrieve data from it using setter and getter functions.
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
Encapsulation in Java −
- Declare the variables of a class as private.
Ex -:
class School
private int index_ num;
private String Stu_ name;
private String Tea_ name;
private int reg_year ;
}
class Run{
psvm(String [] args){
School s = new School ;
s. index_num = 2673;
s.name = "malshan";
s.Tea_name ="madusha";
s. reg_year= 2005;
}
}
The public set() and get() methods are the access points of the instance variables of the Encapsulation Test class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters.
Provide public setter and getter methods to modify and view the variables values.
public void setINDEX_NUM( int index_ num){
this. Index_num= index_num;
}
public void setINDEX_NUM( ){
return. Index_num;
}
Ex-
class Area {
// fields to calculate area
int length;
int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
// method to calculate area
public void getArea() {
int area = length * breadth;
System.out.println("Area: " + area);
}
}
class Main {
public static void main(String[] args) {
// create object of Area
// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle. GetArea();
}
}
Comments
Post a Comment