Ben
Ben

Reputation: 6227

Usage of method return value in method itself

You can skip the blabla and go the the 'Example beneath'. When creating a method with a given return type, is there an instance of the method returntype created when calling the method ? If I have a User class for example and I create a method with the User return type, is there a new Instance of the User class created inside the method when calling it ? Like can you say that; public Object getObject(...){...} creates an uninitialized object like this: public Object object; which you can use inside the method? And when the return type in the method is called it does this: object = return(); Which returns an Object instance declared inside the method. I know I got it terrible explained maby someone else can edit it to make it more clear to the greater audience of stackoverflow.

Example beneath: For example is this possible in some way:

public UserObject getSomethingDone(User user){ 
getSomethingDone.setSomething(user.getSomething);
return getSomethingDone;
}

Instead of this:

public UserObject getSomethingDone(User user){ 
UserObject userObject = new UserObject();
userObject.setSomething(user.getSomething);
return userObject;
}

EDIT: nvm stupid question because I say it might create an unitialized object instance but of course you can't use an unitialized object instance since it is not initialized untill return. So then this might be possible:

public UserObject getSomethingDone(User user){ 
getSomethingDone = new UserObject();
userObject.setSomething(user.getSomething);
return userObject;
}

but that would not make so much sense.

Upvotes: 0

Views: 1513

Answers (3)

LeleDumbo
LeleDumbo

Reputation: 9340

In short, no. Java (and in particular, C family) doesn't work that way. Looks like you've got some kind of Pascal family background which indeed works the way you said (well, almost, since the return value is uninitialized*).

*: I'm referring to your example, not your question as they're contradicting

Upvotes: 0

Konstantin V. Salikhov
Konstantin V. Salikhov

Reputation: 4653

No, no implicit object creation is performed. In Java you used to explicitly create return object.

Upvotes: 0

alexg
alexg

Reputation: 3045

You could get the return type of the method using the reflection API, but it would be a lot more trouble than it is to simply instantiate a new object of the return type.

Upvotes: 1

Related Questions