I have a function that returns a user-defined object. First I want to know if that object is returned by reference and what if it was private?
Also, how do I return it as Constant (final) reference because I don't want someone to mess with it? I'm so confused between returning an object and returning object.copy(); or object.clone();
Java doesn't copy the object, it passes the object reference to the method, and returns it when you use return. The only time where it copies the value is when you use primary types, like int , char or double.
User-defined functions and class methods can define return types as object references (as class or interface types). When an object is passed locally, class instances are always returned by reference. Thus, only a reference to an object is returned, not the object itself.
Returning “this” return this; When you return "this" from a method the current object will be returned.
When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function. The syntax for defining a function that returns an object by value is. 1.
In Java, You always return a reference (unless returned value is a primitive type such as int
, float
, char
, ...).
So, if you don't want the returned object to be modified, you must return a full copy of it (you could use Clonable
interface and clone
method if your class defines it).
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