0
$\begingroup$

Out of the following, which type can cause problems with encapsulation?

A. Int

B. Int[]

C. String

D. non of the above

I chose D and was incorrect. I am kind of confused what this questions is asking about... I just began to learn about the encapsulation and it seems it's just to keep the fields private and not changeable from outside of the class. Why would any type cause problems?

$\endgroup$
2
  • $\begingroup$ The only problem that can be caused with encapsulation, is you not implementing the type with the encapsulation ideas in mind. There is no inherent "problem" for any of those types when dealing with encapsulation. In your place, I would ask your teacher what they meant in this question - because - it really is ambiguous (and hence it is expected that you were confused). $\endgroup$
    – nir shahar
    Commented Nov 22, 2021 at 11:41
  • $\begingroup$ @nirshahar Okay! Thanks for the comment. I will keep that in mind. $\endgroup$ Commented Nov 22, 2021 at 19:04

1 Answer 1

1
$\begingroup$

I think it should be (B) because when using implement get method to get the array will be able to change the array even if it's private through the getter because the "get" method will return a reference to the array, not the array itself.

Check this link

$\endgroup$
3
  • $\begingroup$ In this case what about string which is also an object? The get method may return the reference of the string instead a copy of it.. $\endgroup$ Commented Nov 22, 2021 at 10:40
  • $\begingroup$ Yes, it's returning a reference, I think in this case though your returned unmodifiableCollection would be 'read only' and would not be modifiable. Check this link: docs.oracle.com/javase/7/docs/api/java/util/… $\endgroup$ Commented Nov 22, 2021 at 11:55
  • $\begingroup$ Okay. Thank you! $\endgroup$ Commented Nov 22, 2021 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.