Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive and Non Primitive types getters/setters and initialization

Tags:

java

primitive

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?

like image 868
mu_sa Avatar asked Nov 30 '22 06:11

mu_sa


2 Answers

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

like image 42
guitarflow Avatar answered Dec 10 '22 23:12

guitarflow


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.

like image 52
NPE Avatar answered Dec 10 '22 23:12

NPE