0

What is encapsulation?

encapsulation

28th Feb 2017, 8:38 AM
Devaraj Harikrishnan
Devaraj Harikrishnan - avatar
2 Respostas
+ 2
You can hide the values in a class, and other classes can reach the values with methods. That's why you have to create the values whit private access modifier and the methods are usualy public. The methods wich reach the values are usualy setters and getters and this methods are publics. As a result: 1. Your values are accessible only through the methods of the current class. This is the data hiding. 2. The program more flexible and we can easily modify the code because tha changing has not affect to other parts. This is a fundamentals of encapsulation. In the Java cours you can find a good example in the "More onClasses/Encapsulation" chapter where the code shows an BankAccount class! It is worth look through!
28th Feb 2017, 9:54 AM
Zoltán Bolodár
Zoltán Bolodár - avatar
+ 2
When we making all the data members of the class private. And when we adding only set or get method we make the class read-only or write-only. EXAMPLE: public class A { private int age = 100; private void setAge(int newAge){ this.age = newAge; } public int getAge() { return this.age; } public static void main(String[] args) { // only here we have full control A a = new A(); // is readable only a.setAge(101); System.out.println( a.getAge() ); } } public class B { public static void main(String[] args) { A a = new A(); // is readable only //a.setAge(101); can not be used in other class System.out.println(a.getAge()); } }
3rd Mar 2017, 11:23 AM
Milen Hr.Ivanov
Milen Hr.Ivanov - avatar