Should getters just return the object:
public MyObject getMyObject() {
return myObject;
}
Or should it make a copy of the object it’s returning and return the copy?
public MyObject getMyObject() {
MyObject tempObject;
// call setters to set its attributes
return tempObject;
}
High school “CS” courses here aren’t detailed enough. My teacher never talked about classes, objects, and references.
This depends on what you’re trying to do.
In general, though, you just want a reference to the object, and you use your first code example. For example, Swing components have a method called
getTopLevelAncestor(). It’s completely useless to have a copy of the parent component–what’s wanted is a reference to the child’s actual parent.Returning a copy is not standard, and should only be used under very specific (and well-documented) circumstances. Other people using your code will not expect to get copies of objects.