Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java (beginner) : returning an object ? is it returned as a constant reference or what?

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();

like image 312
Ismail Marmoush Avatar asked Nov 17 '10 14:11

Ismail Marmoush


People also ask

What does returning an object mean Java?

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.

Are objects returned by reference?

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.

What happens when you return this in Java?

Returning “this” return this; When you return "this" from a method the current object will be returned.

What is a returning object?

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.


1 Answers

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).

like image 104
Pablo Santa Cruz Avatar answered Sep 21 '22 06:09

Pablo Santa Cruz