Are Java non-primitive (object) data types treated in the same way as primitive data types? By treatment I mean...
1 : Should they be private in the class?
2 : Should they be initialized to some value during the declaration? (e.g. String S = ""
instead of String S
)
3 : Should they have getters and setters too?
to 1 : of course, that's the principle of information hiding
to 2 : Many of them are already initialized "under the hood", but you should better do it yourself
to 3 : of course, also information hiding
Best, Flo
The simple answer to all three questions is "yes". The three practices are sound irrespective of whether the variable in question is of a primitive type.
One gotcha to be aware of is that, if you have a reference to a mutable object, and your getter returns that reference, this potentially permits the caller to modify the object (which you thought was private to your class!)
Another difference between the two cases is that object references can be set to null
. This can be useful, but can also be a source of errors. It is perhaps worth pointing out here that String s = null
and String s = ""
are not the same.
Finally, with objects it is important to understand the difference between obj1 == obj2
and obj1.equals(obj2)
. This distinction doesn't arise with primitive types, since there's only one way to compare them for equality.
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