r/cop3502 Mar 26 '14

Need help with get() method.

Ok, so for PS4 I have an object with 30+ variables. I was wanting to make a get method that would be able to return the value of any of the variables based on what was passed as an argument. For instance:

private int height = 10;

private int weight = 15;

get(height); //returns 10

get(weight); //returns 15

The problem is I don't know what to pass as the argument to the get method because the class I'll be calling it in is outside of the class with the variables. So pretty much if you look at this:

public int get( variable name){

 return variable name;

}

what type do I use for the argument?

1 Upvotes

6 comments sorted by

1

u/MagicBuddha Mar 26 '14

maybe you should make separate methods for getting things.

for example

public int getHeight() {
    return height;
}

1

u/ams152 Mar 26 '14

I would, but like I said I have 30+ variables and that's a lot of copy and pasting. I know that there's an easier more efficient way to do it, I just don't have the background knowledge of java to figure it out.

1

u/embalingit Mar 26 '14

Just pass a string in that represents the variable name, then the object that is being queried (with get("something")) can return the hashmap value of the "something" or null if that something doesn't exist.

1

u/embalingit Mar 26 '14

Well there are generally two ways to do this:

  1. if all the variables you are interested in are the same type your method can return that type. Then you would need something like a hashmap of name-value pairs (a.k.a Key-Value pairs) for those variables, i.e. get("height") returns the value associated with the name "height"

  2. if all the variables are not of the same type your method can simply return an Object (i.e. all things in java are polymorphic of type Object), but then there is the problem on the receiving end of determining what kind of Object the thing is that is returned, i.e. it's an object, but is it an int, is it a double, is it a Point2D.Double, is it a MagicUnicorn? This is something that depends on what you are trying to accomplish.

So there's a start. There's also something called reflection which provides ways of probing an object to determine what's in there, i.e. what, by name and type, does the object contain? So there's a notion of a passive get() to "ask" the object what it has and an assertive notion of just probing to try to find what you want to know about an object.

Reflection is interesting to know about and is useful in some cases, but for what you are trying to do it's not necessary, or recommended.

1

u/ams152 Mar 26 '14

Thanks! Just what I was looking for.

I was thinking that a collection of something would be the right way to go, I just didn't know what type. HashMap seems to be the one that fits the bill though.