Because Java is OOP. Using object's fields directly (by publishing them) is not OOP.
As you see, getters and setters are not only be used to set the value to the fields and get the value from the fields, but also for some background tasks.
Sorry for my English...
Joined: Oct 04, 2006
yes i agree with you and what my understanding is same as you said.
we are working with Java then we first have to implements the OPPS concept and this is one the property of Opps is encapsulation which says member variables of class should not expose to real world or another application. So we are making it private and methods are able to access that members.
but someone is saying its the books theory so any practical example or scenario where you really can see the importance of making getter/setter methods.
i agree with 1 point only with given by seetaraman.
Prabhat Ranjan wrote:it is correct that if we have some business logic written in setter methods then it is good to use that way. this is one of the valid point and what else we can say
Remember that the getter/setter approach is essential if they will contain any business logic either now or at any point in the future. If you've encapsulated the properties, you can add validation, change the implementation, etc, any time you want with no effects elsewhere. If you haven't, then when you try to introduce it in the future you will break all existing code that refers to the member variables. This is tight-coupling (a bad thing) - other classes should interact only with a class' public interface, and shouldn't care at all about its implementation.
So omitting setters and getters can only be acceptable if you can be certain that the implementation is absolutely fixed for all time, and you (or other maintenance programmers) will never want to add business logic. Which is close to impossible.
The cost of encapsulating the properties is very small (lines of code is pretty irrelevant, especially with IDE support). The one time it turns out to be useful will save you lots of problems. It's best to get into the good habit now.