Skip to main content
gamedev.net
🔒 Locked

Returning an Object [Java]

Started by Cuajin Nov 8, 2011 at 5:09 AM 2 replies 850+ views
Original Post
Cuajin
Cuajin
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));



SenatorBobDole
SenatorBobDole
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.
Cuajin
Cuajin

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.
rip-off
rip-off
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.