• Advertisement
Sign in to follow this  

Returning an Object [Java]

This topic is 2298 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have two classes, one class has a method type as the name of the other class. I want to return an object and print it in main.


Please help. I have tried different versions some dont compile, but the one below does. Although it compiles it just outputs a random number which I am guessing is a memory location.



public class Big
{
public Big()
{

}

public AnotherClass getNumber(int x)
{
AnotherClass obj = new AnotherClass(1, 2, 3);

obj.getY(); // a method inside the Class named AnotherClass

return obj; // I want to return this object, but of course this fails.
}
}


// in main
Big bigObj = new Big();

System.out.println(bigObj.getNumber(5));



Share this post


Link to post
Share on other sites
Advertisement
Your method getNumber is returning a reference to an object, essentially a pointer. So you're printing a pointer which is a memory address, and that is why it seems like you're printing a random number.
If can either have getNumber return the number that you want, or you can over ride the objects toString method to print what you want. A couple options for you.

Share this post


Link to post
Share on other sites

Your method getNumber is returning a reference to an object, essentially a pointer. So you're printing a pointer which is a memory address, and that is why it seems like you're printing a random number.
If can either have getNumber return the number that you want, or you can over ride the objects toString method to print what you want. A couple options for you.



Can you show me how you would print it? I can't get it to work.

Share this post


Link to post
Share on other sites
What does "I can't get it to work mean". What did you try?

An interesting thing to research: when you print an object, what happens? Not what you expect to happen, but look into the detail of what happens when you pass an object to System.out.

[hr]

Now that you've done some research, you'll know that if you want to print the field values, you're going to have to do this yourself. One option is to implement AnotherClass#toString(), and in your implementation include the field values in the returned string.

Another is to print the values at the call site:

// in main
Big bigObj = new Big();

AnotherClass another = bigObj.getNumber(5);

System.out.println("Number 5 {");
System.out.println("\tx: " + another.getX());
System.out.println("\ty: " + another.getY());
System.out.println("\tz: " + another.getZ());
System.out.println("}");

This would be a better solution if you have particular formatting requirements at the call site.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement