+ 1
I am not getting encapsulation!
can anyone refer me a detailed something.
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);
+ 3
https://www.sololearn.com/discuss/1104179/?ref=app
https://www.sololearn.com/discuss/1827356/?ref=app
https://www.sololearn.com/discuss/1084983/?ref=app
https://www.sololearn.com/discuss/344066/?ref=app
https://www.sololearn.com/discuss/1807703/?ref=app
https://www.sololearn.com/discuss/550564/?ref=app
https://www.sololearn.com/discuss/1569093/?ref=app
https://www.sololearn.com/discuss/967225/?ref=app
https://www.sololearn.com/discuss/1012247/?ref=app
https://www.sololearn.com/discuss/267804/?ref=app
https://www.sololearn.com/discuss/1747523/?ref=app
https://www.sololearn.com/discuss/860433/?ref=app
https://www.sololearn.com/discuss/1128076/?ref=app
+ 1
It means data can be grouped together. That's just what an object means.
+ 1
https://en.m.wikipedia.org/wiki/Encapsulation_(computer_programming)
+ 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.