0

I create an object in , lets say a square and I want to make many copies of square with different coordinates so I can call it with

Square square = new Square(int x, int y)

Inside square I created a method that changes the square color. What I'm trying to do is create multiple instances of square

square = new Square(2, 4);
square = new Square(9, 7);
.
.
.

and when I call square.changeColor() I want all of them to change, what would be the best way of doing this?

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
Mark
  • 29
  • 3

2 Answers2

0

Use a static variable for color, that way there will be one across all instances.

meanderingmoose
  • 250
  • 1
  • 3
  • 10
  • I have the method public static void stop() { square.setGravityScale(0f); square.setLinearVelocity(Vars.scrollSpeed / PPM, 0); } square is a box2d object so it moves from right to left, when I call the methos stop it works no problems. when I create many squares for(i=0; i<5; i++){ Square square = new Square(); } this creates 5 squares with the same name (all called "square") when I call square.stop() only the last one created stops, how can I make that all of them execute the stop method? – Mark Jul 22 '14 at 21:17
  • Or should I create a list of objects and call the method on each one of them – Mark Jul 22 '14 at 21:23
  • You can make the variable representing the speed static as well, but this will mean that all your squares constantly move the same speed. You could also create a new static variable, boolean stop, and have the squares only move if stop is false, then change it to try in your method. – meanderingmoose Jul 22 '14 at 21:35
0

Make Color in the square class static.

What are static variables?

A simplified explanation of it would be that when you make a change in an Object(Square) of a particular static variable(Color). It will change across all instances of the object (Square).

More information:

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

progrenhard
  • 2,333
  • 2
  • 14
  • 14