I'm wondering about why to use getter and setter methods in java. If you can read or modify values of private fields via getters and setters, why not just changing them directly to public? I know that getters and setters have to be reasonable, but what would be the straight answer that it's not possible to give up on them?
Some reasons are:
setter
to ensure that no other values are set on the attribute.getter
only.See the answers in the link provided by @Aditi for additional reasons: Why use getters and setters?
One of the hardest forms of bug to track down is an unexpected, inappropriate change in the value of a data item.
If the data is public, the code that makes the change could be anywhere in the program.
If it is private, the code that makes the change must be in the same source file, typically the same class. It is easy to find and instrument all code that could possibly change it, including its setter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With