1

如果我在“”之前插入以下内容public GUI(),警告就会消失,但发生了什么?

  @SuppressWarnings("OverridableMethodCallInConstructor")

我真的应该怎么做?为什么?

public class GUI extends javax.swing.JFrame {

  boolean plusActive;
  boolean minusActive;
  boolean timesActive;
  boolean divActive;
  boolean toTheActive;

  public GUI() {
    initComponents();
    zapOperatorBooleans();
  }

  public void zapOperatorBooleans(){
    plusActive = false;
    minusActive = false;
    timesActive = false;
    divActive = false;
    toTheActive = false;
  }
  ...

我刚刚读到(在工具>选项>提示中)“调用可以被覆盖的方法在构造函数中可能很危险,因为在调用被覆盖的方法的那一刻,对象没有完全初始化”但这无助于我决定我该做什么。

4

2 回答 2

1

声明zapOperatorBooleansfinalprivate。至于为什么,见http://www.javapractices.com/topic/TopicAction.do?Id=215

于 2013-10-24T00:13:37.210 回答
0

All the comments helped. Here's the modified code. I only had what I had before because GUIbuilder tempted me with its initComponents() method and I lunged at the chance and fell off the ledge.

class...
      private static boolean plusActive = false;
      private static boolean minusActive = false;

etc.

  public GUI() {
    initComponents();
  }

  private void zapOperatorBooleans(){
    plusActive = false;
    minusActive = false;

etc.
(Not redundant; one or more of those booleans get set to true during iterated executions of the GUI and need to be reset, but they need initial values, too.)

So THAT'S what I REALLY should have done.

More importantly (from my standpoint), my ignorance of such a fundamental concept and others (e.g., my clueless response to the error message "Non-static ... may not be referenced from a non-static context") made me do quite a bit of reading, reflecting (personal, not Java), Googling, studying, thinking... and I am far better off than I was.

于 2013-10-25T21:23:54.470 回答