How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define
get
methods to access these variables, andset
methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.For example, for a member variable:
You might have methods:
chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public
get
method and keeping theset
private or not providing aset
at all.I want to add to other answers that setters can be used to prevent putting the object in an invalid state.
For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:
However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:
The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.
Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:
I think you want something like this:
You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:
Of course this can be dangerous if somebody forgets to call
setAge(int)
where he should and setsage
directly usingthis.age
.