Reputation: 63
I simply want to increment a variable, numOfBodies, as a new Body is created and use this value in my main class. Why is it not working properly? I though this was the way the static keyword worked?
int deltaTime = 500*Body.getNum();
public class Body {
public static int numOfBodies;
public Body(){
numOfBodies++;
}
public static int getNum(){
return numOfBodies;
}
}
Upvotes: 0
Views: 75
Reputation: 285405
Based on this comment:
I didn't think it was relevant to the question. I am of course creating bodies once I start the program, by pressing 'm'. What I want is for deltaTime to update as I press 'm' more times i.e creating more bodies
It seems like my guess is correct, that you're assuming that deltaTime will automatically increment whenever a new Body is created, and that is not how Java works. In order for that to happen you need to explicitly update deltaTime. One way is to use an observer design pattern, perhaps using PropertyChangeSupport to update deltaTime whenever a new Body is created.
Although having said that, I've never used a PropertyChangeListener to listen to a static property before.
But for example:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Scanner;
public class TestBody {
private static final String QUIT = "quit";
public static int deltaTime = 0;
public static void main(String[] args) {
Body.addPropertyChangeListener(Body.NUM_OF_BODIES,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
deltaTime = 500*Body.getNum();
System.out.println("deltaTime: " + deltaTime);
}
});
Scanner scan = new Scanner(System.in);
String line = "";
while (!line.contains(QUIT)) {
System.out.print("Please press enter to create a new body, or type \"quit\" to quit: ");
line = scan.nextLine();
Body body = new Body();
}
}
}
class Body {
public static final String NUM_OF_BODIES = "num of bodies";
private static PropertyChangeSupport pcSupport = new PropertyChangeSupport(
Body.class);
private static volatile int numOfBodies;
public Body() {
int oldValue = numOfBodies;
numOfBodies++;
int newValue = numOfBodies;
pcSupport.firePropertyChange(NUM_OF_BODIES, oldValue, newValue);
}
public static int getNum() {
return numOfBodies;
}
public static void addPropertyChangeListener(PropertyChangeListener l) {
pcSupport.addPropertyChangeListener(l);
}
public static void removePropertyChangeListener(PropertyChangeListener l) {
pcSupport.removePropertyChangeListener(l);
}
public static void addPropertyChangeListener(String propertyName,
PropertyChangeListener l) {
pcSupport.addPropertyChangeListener(propertyName, l);
}
public static void removePropertyChangeListener(String propertyName,
PropertyChangeListener l) {
pcSupport.removePropertyChangeListener(propertyName, l);
}
}
Upvotes: 1