💻Step 16:Oops- 4th Concept: Encapsulation: 11th hour + code

Learn with youtube video-

💡Definition-

Encapsulation_in_Java[1]

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 –

ConceptDefinitionReal-World Example
AbstractionHiding implementation details and showing only the functionality to the userThe “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.
EncapsulationWrapping data (variables) and code (methods) together as a single unitThe 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());
}
}

 

Run this Program ▶️

Interview Questions —

  • what is encapsulation ?
  • How data security is achieved in java?

Leave a Reply

Your email address will not be published. Required fields are marked *