raja singh kumar wrote:. . . Is Example 2 also an example of fully encapsulated class. . . .
No. Neither example is fully encapsulated; both sacrifice encapsulation if they have the setXXX methods because they allow the state of the object to change. Full encapsulation and the bean
pattern which requires the setXXX and getXXX methods are mutually incompatible.
Find a copy of
Effective Java by Joshua Bloch and find the chapter about defensive copies. You will then find out that the difference is not between primitives ad reference types, but between mutable and immutable fields. Strings are immutable, so the state of the
String can no more change than the state of an
int. If you return a String reference, you cannot get any problems (unless somebody is doing some very naughty reflection
). If however, you return a mutable reference type (e.g. an array), the state of that array can be changed elsewhere and that changes the state of your current object.