我已经开发示例项目作为类变量(静态)的证明概念。但是当我运行StaticCounter.java
该类的两个实例时,共享变量(静态)会给这两个实例不同的引用?!!。
- 类变量(静态字段) 类变量是使用 static 修饰符声明的任何字段;这告诉编译器存在该变量的确切副本,无论该类已被实例化多少次。定义特定类型自行车的齿轮数量的字段可以标记为静态,因为从概念上讲,相同数量的齿轮将应用于所有实例。代码 static int numGears = 6; 会创建这样一个静态字段。此外,可以添加关键字 final 来表示齿轮的数量永远不会改变。
的代码StaticCounter.java
:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StaticCounter extends JFrame {
public static int COUNTER = 0;
private JButton btnCounter;
private JButton btnShowValue;
private JLabel lblCounter;
public StaticCounter() {
initComponents();
}
private void initComponents() {
btnShowValue = new JButton();
btnCounter = new JButton();
lblCounter = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
btnShowValue.setText("Show Value");
btnShowValue.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
showValue(evt);
}
});
btnCounter.setText("Counter +1");
btnCounter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
doCount(evt);
}
});
lblCounter.setFont(new Font("Tahoma", 1, 36));
lblCounter.setText("0");
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup( GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup( GroupLayout.Alignment.LEADING)
.addGroup( GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnCounter)
.addPreferredGap( LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnShowValue))
.addComponent(lblCounter, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap()));
layout.setVerticalGroup(
layout.createParallelGroup( GroupLayout.Alignment.LEADING)
.addGroup( GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblCounter, GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE)
.addPreferredGap( LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup( GroupLayout.Alignment.BASELINE)
.addComponent(btnShowValue)
.addComponent(btnCounter))
.addContainerGap()));
pack();
}
private void doCount( ActionEvent evt) {
++StaticCounter.COUNTER;
lblCounter.setText(String.valueOf(StaticCounter.COUNTER));
}
private void showValue( ActionEvent evt) {
JOptionPane.showMessageDialog(null, String.valueOf(StaticCounter.COUNTER));
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new StaticCounter().setVisible(true);
}
});
}
}
现在如果你运行它两次或三次,静态将是实例变量而不是类变量?但是,如果我在一次类的运行中将主初始化更改两次或三次,它可以正常工作吗?
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new StaticCounter().setVisible(true);
new StaticCounter().setVisible(true);
}
});
}
}
所以为什么?!