【问题标题】:Advantage of declaring and instantiating variables in java GUI constructorjava GUI构造函数中声明和实例化变量的优点
【发布时间】:2014-02-14 14:25:44
【问题描述】:

在构造函数中声明+实例化变量,而不是在外面声明然后在构造函数中实例化,甚至在外面都声明+实例化有什么好处?

public class GUIview extends JFrame {
   public GUIview() {
       JPanel pan = new JPanel();
       JSplitPane splitPane = new JSplitPane();
    }
   public static void main(String[] args) {
       GUIview view = new GUIview();
       view.setVisible(true);
    }
}

public class GUIview extends JFrame {

   JPanel pan;
   JSplitPane splitPane;

   public GUIview() {
       pan = new JPanel();
       splitPane = new JSplitPane();
    }
   public static void main(String[] args) {
       GUIview view = new GUIview();
       view.setVisible(true);
    }
}

【问题讨论】:

  • 好吧,首先,像这样在构造函数中声明的变量会立即超出范围进行垃圾回收......

标签: java user-interface constructor declaration instantiation


【解决方案1】:

我假设代码被缩短以便可以在此处发布。但我也假设省略了一个重要部分 - 即组件被添加到框架或其他容器中:

public GUIview() {
    JPanel pan = new JPanel();
    JSplitPane splitPane = new JSplitPane();

    // This was omitted
    pan.add(splitPane);
    this.add(pan);
}

如果这是正确的,那么一般的陈述可能是:在构造函数中声明变量的好处是你的类不会被不必要的字段弄乱!

这很重要:您不应该将 GUI 组件作为字段存储在您的 GUI 类中,除非您需要访问它们。例如:

class GUI extends JPanel
{
    // This component has to be stored as a field, because
    // it is needed for the "getText" method below
    private JTextField textField;

    public GUI()
    {

        // This component will just be added to this panel,
        // and you don't need a reference to this later. 
        // So it should ONLY be declared here, locally
        JLabel label = new JLabel("Enter some text:");
        add(label);

        textField = new JTextField();
        add(textField);
    }

    public String getText()
    {
        return textField.getText();
    }
}

【讨论】:

    【解决方案2】:

    这里没有专门针对 Java 用户界面的特殊规则。

    如果必须从多个方法访问变量,或者必须在调用之间保留其值(好吧,构造函数只调用一次,所以情况并非如此),通常使用字段。

    如果变量只在一个方法中被访问,并且在该方法返回后不再需要它的值,那么将这样的变量声明为字段是没有意义的。

    【讨论】:

      猜你喜欢
      • 2010-12-31
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多