+ 3

Can anybody make a real time program in which encapsulation is being used ?

i understand the concept but getting confuse in implementation

1st Mar 2018, 4:35 PM
Pooja chouhan
Pooja chouhan - avatar
4 odpowiedzi
+ 4
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
1st Mar 2018, 5:16 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
thanks to Jakob Marley and Rahul
2nd Mar 2018, 3:29 PM
Pooja chouhan
Pooja chouhan - avatar
0
encapsulation is used every where when we want to make our code more readable. In encapsulation, basically we divide whole code into capsules( classes and its methods) which is easier to understand. Android app development is a best example for java which uses concepts of encapsulation etc.
1st Mar 2018, 4:41 PM
Rahul saini
Rahul saini - avatar
0
it getting real.Thanks
17th Aug 2018, 8:07 AM
Boniface Musonda
Boniface Musonda - avatar