This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java and have Dr. Raoul-Gabriel Urma & Richard Warburton on-line! See this thread for details.
Encapsulation is one of the OO feature, which will hide the data from external world. One can't access the data directly.
getter and setter method not only provides one way to hide the data, but also will give control to you to perform the validations.
For example, in business and real time applications, there are certain validations, like age must be greater than 3 years. If you have getter and setter methods, you can check before assignment or null check.
Explore more ...
posted 13 years ago
thanks for your time, but can you explain a bit more on that.
Compare these two classes - in the first example if you wanted to disallow certain values for age - you are going to have to refactor the Person class to put a setter in front of it. Where as in the second class all you have to do is add checkes before the "this.age = age" call - of course this method doesn't throw any exceptions so you might have to make more changes than that.
Encapsulation lets you hide the internal struture from the outside world and force them to come from through an API. Then if you can keep the API intact you can make changes internally without anyone else noticing. Its hard to do with something as simple as an Age - but what if you wanted to change how it was stored internally - with your public int age; you can't remove this or rename this variable safely - anyone could be using it. with get/setAge as long as you can still take and return an int - the user doesn't care what you do internally.
The java classes with getter and setters are very much useful for transfering date or to represent a set of data.
Suppose you want to exactly replicate a addressbook in code.You can have a arraylist as the addressbook and can have a class Address with name and phone as private variables and you can have getter and setters for name and phone.use setters to popolate the address object and put in the addressbook (that is the arraylist) and continue with the approach to create address object for each address card , populate the object using the setters and set in the arryalist.Now you have a full address book and you can transfer this to any other interface which knows how to deal with the addressbook.