我只想在创建新 Body 时增加变量 numOfBodies,并在我的主类中使用该值。为什么它不能正常工作?我认为这就是 static 关键字的工作方式?
int deltaTime = 500*Body.getNum();
<小时/>
public class Body {
public static int numOfBodies;
public Body(){
numOfBodies++;
}
public static int getNum(){
return numOfBodies;
}
}
最佳答案
基于此评论:
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
看来我的猜测是正确的,您假设每当创建新的 Body 时 deltaTime 都会自动增加,而这不是 Java 的工作方式。为了实现这一点,您需要显式更新 deltaTime。一种方法是使用观察者设计模式,也许在创建新 Body 时使用 PropertyChangeSupport 来更新 deltaTime。
尽管如此,我以前从未使用过 PropertyChangeListener 来监听静态属性。
但例如:
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);
}
}
关于java - 创建对象时增量计数器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110172/