Originally Posted by
MuthuKumar
Using getter and setter- to make your variable to private. Nobody can access it directly from outside
This is correct, but there are more important ideas here. The point of OO software is reuse. This means that other programmers, or you years from now, can use the code for other systems.
When you have private member variables, and use get/set functions, you can change the internal implementation of the function without breaking all the other code that uses it.
Consider a class using a US telephone number. They are typically displayed as (nnn) nnn-nnnn such as (800) 555-1212
A naive implementation may make this just a ten character String. Or even just a String without length. And it will work.
But suppose you start to work for a cell phone company. For them, the same telephone number is not one String, its three separate and important fields:
- Area code
- exchange (aka CO)
- line
If you implement your class and have getPhoneNumber() and setPhoneNumber() and then implement the separate fields, you can easily add
- getAreaCode()
- setAreaCode()
- getExchange()
- setExchange()
- getLine()
- setLine()
and do all sorts of special handling, validate area codes, etc. All while
Not breaking existing users of the class.