Many times when y'all volition larn to attend WebDriver Interview on 2+ years experience, Interviewer volition inquire y'all about Encapsulation. Best response on Encapsulation In Java software evolution linguistic communication Is equally bellow.
Encapsulation
Encapsulation In Java software evolution language Is i of the OOP key concept. It Is procedure of packing code as well as information together In to a unmarried Unit. Best representative Is capsule where pulverisation of several medicines Is packed In unmarried unit.
It Is too known equally "data hiding" technique equally fields of flat are declared somebody and providing access to the fields via world methods. So anyone tin non access somebody information fields straight exterior the class. We tin role setter as well as getter methods to larn as well as ready information In to It.
Advantages of Encapsulation
Few advantages of encapsulation.
- It Increase the usability.
- It promotes the slow maintenance inward coffee software development.
- It makes the flat slow to role for clients.
- Data access as well as alteration control.
- It Is slow to alter i business office of code without affecting other business office of code.
Example of Encapsulation
Let's expect at really elementary representative of encapsulation In java software evolution language . I accept created encapsulation flat Encaps.java equally bellow.
Encaps.java
package oopbasics; world flat Encaps { somebody String name; somebody int rollNo; //Data setter method world void setName(String newName) { refer = newName; } //Data setter method world void setrollNo(int newrollNo) { rollNo = newrollNo; } //Data getter method world String getName() { provide name; } //Data getter method world int getrollNo() { provide rollNo; } }
In inward a higher house class, I accept created information setter as well as getter world methods to ready as well as larn data. All variables are declared equally somebody to no i tin access as well as modify them straight from exterior the class.
Now nosotros tin ready as well as larn values from Encaps.java flat equally bellow.
Encaps.java
package oopbasics; world flat exeEncaps { world static void main(String[] args) { //Created object of Encaps flat to ready as well as larn data. Encaps encaps = novel Encaps(); //Set information using setter methods of Encaps class. encaps.setName("Monika"); encaps.setrollNo(56); //Get information using getter methods of Encaps class. System.out.println("RollNo : "+encaps.getrollNo()+", Name : "+encaps.getName()); } }
Output of inward a higher house representative Is equally bellow.
RollNo : 56, Name : Monika
This Is the best explanation of encapsulation. You tin honour to a greater extent than links to read basic java software evolution tutorials on THIS PAGE.