This website includes Education Information like a programming language, job interview question, general knowledge.mathematics

Education log

PageNavi Results No.

Ads

Wednesday, February 22, 2023

What is encapsulation explain with example

 What is encapsulation explain with example


Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines.


encapsulation in java

We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.


Encapsulation in Java refers to integrating data (variables) and code (methods) into a single unit. In encapsulation, a class's variables are hidden from other classes and can only be accessed by the methods of the class in which they are found.


What is encapsulation in Java with realtime example?

Every Java class is an example of encapsulation because we write everything within the class only that binds variables and methods together and hides their complexity from other classes. Another example of encapsulation is a capsule. Basically, capsule encapsulates several combinations of medicine.



Example encapsulation in java:


package com.javaencapsulation;  

public class Student{  

//private data member  

private String name;  

//getter method for name  

public String getName(){  

return name;  

}  

//setter method for name  

public void setName(String name){  

this.name=name  

}  

}  

No comments:

Post a Comment