
Play Store Application link – https://play.google.com/store/apps/details?id=com.ideepro.java25hours
Learn with youtube video-
💡Definition-
![Encapsulation_in_Java[1]](https://corejava25hours.com/wp-content/uploads/2021/02/encapsulation_in_java1.png)
Encapsulation is a concept of binding data and code together in single unit.
-In java, data means data members, and code means methods.
– In java, in encapsulation, data members are private and access methods (setters and getters) are public.
NOTE- Both abstraction and encapsulation have many similarities, here are comparison between both with real world example –
Concept | Definition | Real-World Example |
---|---|---|
Abstraction | Hiding implementation details and showing only the functionality to the user | The “Call” button on a phone hides the complex process of establishing a connection to another phone, and allows the user to simply initiate a call with a single button press. |
Encapsulation | Wrapping data (variables) and code (methods) together as a single unit | The battery of a phone is encapsulated within the phone’s casing, protecting it from external access or tampering. |
1- Creation of encapsulation class-
package ncapsulsn; public class ExEncapsulated { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2- Usege of encapsulation class-
package ncapsulsn; public class UseEncapsulated { public static void main(String[] args) { ExEncapsulated e1=new ExEncapsulated(); e1.setName("xyz"); e1.setAge(5); ExEncapsulated e2=new ExEncapsulated(); e2.setAge(17); System.out.println(e2.getAge()); } }
Interview Questions —
- what is encapsulation ?
- How data security is achieved in java?