I am not getting encapsulation! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I am not getting encapsulation!

can anyone refer me a detailed something.

19th Aug 2019, 8:22 PM
Mehedi Hassan
5 Answers
+ 4
An easy way to understand this is to create a class with a private variable and a public variable and try and accsess these outside of that class in main. You will notice when you create an object of that class you can accsess the public variable directly (obj.var1=10;) but not the private one (obj.var2=10; (gives error). The only way to change that private variable outside of that class is to use a method usually called setter method but you can call it anything you like. public class A{ private String var2; //when this method is called it will set my variable with the value of x. public void setMyPrivateField(int x){ this.var2=x; } } A a = new A().setMyPrivateField(10);
19th Aug 2019, 8:50 PM
D_Stark
D_Stark - avatar
+ 1
It means data can be grouped together. That's just what an object means.
19th Aug 2019, 8:27 PM
Airree
Airree - avatar
19th Aug 2019, 10:16 PM
HonFu
HonFu - avatar
+ 1
Para los que hablamos español, la encapsulacion es la forma de restringir una variable o un metodo para que desde afuera de su clase no se le permita visibilidad por lo tanto no es posible aplicarle cambios, eh aqui es donde se acude a los metodos set y get para poder asignarle nuevos valores y poderlos mostrar en pantalla. Sin estos dos ultimos metodos mencionados su accesibilidad a una variable que esta declarada private sera imposible su manipulacion. Y esto ayuda a mas adelante tener un mayor nivel de seguridad en nuestros codigos, ya que cualquiera no podra adulterarlos facilmente.
25th Aug 2019, 3:51 PM
Daniel Felipe George
Daniel Felipe George - avatar