+ 5
I wrote to someone else about this last week, so I'm just going to copy/paste my answer to you. The example I typed up is in Java, but C# and Java are very similar, so you should be able to translate it. If not, let me know and I'll type it up in C#.
----------------------------------------
Encapsulation is a means of wrapping the variables of your class so that they're isolated to the class and not accessible from the rest of the program. You use setters/getters in order to access and manipulate those variables when you need to. It's a great means of keeping it secured.
The rest of your program never directly touches the variables and they'll remain private to the class. As you can see, the method we created allow us to do what we need to do while keeping those variable secured in the class.
https://code.sololearn.com/c1GpM7SM1qE5/#java
class MyClass {
// Since we're using encapsulation, make your class members private
private int myInt;
private String myStr;
public MyClass(){
this.myInt = 0;
this.myStr = "N/A";
}
// setters
public void setInt(int myInt){
this.myInt = myInt;
}
public void setStr(String myStr){
this.myStr = myStr;
}
// getters
public int getInt(){
return this.myInt;
}
public String getStr(){
return this.myStr;
}
}
public class Program
{
public static void main(String[] args) {
MyClass obj = new MyClass();
// Display default values with your getters
System.out.println("Default Int: " + obj.getInt());
System.out.println("Default Str: " + obj.getStr());
// Use setters to change values
obj.setInt(5);
obj.setStr("New String");
// Display new values with your getters
System.out.println("New Int: " + obj.getInt());
System.out.println("New Str: " + obj.getStr());
}
}
::::::: OUTPUT ::::::::
Default Int: 0
Default Str: N/A
New Int: 5
New Str: New String
+ 2
encapsulation is hiding data and provide some safe or secure way to reach the data not to directly access to them.
i think you feel confuse because using properties such as get set
don't mind my English toođ
+ 1
Can you show me your code how you access private attributes?