Results 1 to 2 of 2
- 02-28-2012, 08:59 AM #1
Member
- Join Date
- Feb 2012
- Posts
- 4
- Rep Power
- 0
Variable argument lengths passing by reference issues
I'm making an android game and I've created a button class, which my various buttons can all be subclasses of, and each implements the abstract "onPress" method. Since the onPress will do a variety of things depending on the button, I figured the generic Object... parameter made the most sense. But when I went to create my first button, which simply inverts a boolean when pressed, it doesn't seem to take.
in the main class:
boolean turretMenuOpen = false;
Turret_menu_button button = new Turret_menu_button;
.....
button.onPress(turretMenuOpen);
.....
in the superclass:
public abstract void onPress(Object... objects);
in the subclass:
@Override
public void onPress(Object... objects) {
objects[0] = !((Boolean)objects[0]).booleanValue();
}
I can see that I'm getting the boolean passed ok, it's false when it's in the onPress method. But my assignment doesn't ever actually change the value of the variable in main. Even if I just assign it directly to true, it's still false in main. Why isn't it sticking? I thought it might be a reference/value thing, but it seems like directly assigning it a value should definitely change the object it's pointing to. I even tried changing it to the nonprimitive Boolean, but it didn't make any difference. Halp!
- 02-28-2012, 10:34 AM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Re: Variable argument lengths passing by reference issues
Under the hood the compiler is doing:
That array is passed into the method call.Java Code:boolean turretMenuOpen = false; Boolean[] temparray = new Boolean[1](); temparray[0] = turretMenuOpen;
Now, if you wrote that directly into code as follows:
You'll see that 'b' doesn't change, it is still true.Java Code:public class Scratch { /** * @param args */ public static void main(String[] args) { boolean b = true; Boolean[] temparray = new Boolean[] {b}; temparray[0] = Boolean.FALSE; // This represents the method call System.out.println(b); } }
Which is as expected.
The only thing that was changed was the reference inside the temporary array, which is not reflected in 'b'.Please do not ask for code as refusal often offends.
Similar Threads
-
Question on Passing by Reference..
By fatabass in forum New To JavaReplies: 1Last Post: 02-07-2012, 12:02 AM -
change variable given as argument to function
By Danieljabailey in forum New To JavaReplies: 4Last Post: 07-27-2011, 11:48 PM -
Passing method as argument
By susieferrari in forum New To JavaReplies: 26Last Post: 06-13-2011, 10:43 AM -
Reference variable
By lala in forum New To JavaReplies: 2Last Post: 02-03-2011, 07:27 PM -
Passing Class Reference to method
By nekt in forum Advanced JavaReplies: 5Last Post: 03-26-2009, 05:08 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks