Alex Rivera | Logout

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

Asked 2010-11-17T14:28:27.023
17

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

Edit
Report

1 Answer

4

What you should really realize is that there is nothing special about "passing" or "returning". Whenever you "pass" or "return" something, it just passes the value of the thing. Period. For any type. Whenever you "pass" or "return" something, it's exactly the same as simply assigning it to a variable.

However, what is the value of the thing you are passing or returning? That is where your confusion seems to lie. Your question asks about "returning an object"; however, such a thing does not make sense in Java. Objects are not values in Java. It is impossible to have a variable whose value is an object.

The only types in Java are primitive types and reference types. Hence the only values are primitives and references. (References are pointers to objects.) In Java, we only manipulate objects through references (pointers to objects). We cannot store an object in a variable; but we can store a reference (pointer to an object) in a variable. So when you talk about passing or returning objects, you are almost certainly instead talking about passing or returning references. And, as said before, there is nothing special about passing or returning references -- the value of the reference (a pointer) is passed or returned.

answered 2013-02-25T07:37:25.947

Your Answer