简体   繁体   English

Java类子类变量参考

[英]Java Class subclass variable reference

I keep running into the 'cannot find symbol' error on my class. 我上课时一直遇到“找不到符号”错误。 The variable is clearly declared in the super class, yet the subclass can not see it. 该变量在超类中明确声明,但子类看不到它。 I receive no errors except on the new constructor of JLabel in the subclass RecordViewer . 除了在RecordViewer子类中JLabel的新构造函数上,我没有收到任何错误。

 class RecordViewer extends JDialog{
     private JButton next;
     private JButton prev;
     private JLabel label;
     private int current;

     public RecordViewer(CDinventoryItem [] array){
         super();
         current = 0;
         final CDinventoryItem [] items = array;

         label = new JLabel(items[getCurrent()]);

Predefined toString from my CDinventoryItem class... 来自我的CDinventoryItem类的预定义toString ...

        @Override public String toString(){

        //  Decimal foramting for the inventory values
        NumberFormat dformat = new DecimalFormat("#0.00");

        //  Formatting for the inventory output
        StringBuilder ouput  = new StringBuilder();
        String New_Line = System.getProperty("line.separator");

            ouput.append("The product number of my CD is: ").append(iPitemNumber).append (New_Line);
            ouput.append("The title of the CD is: ").append(sPtitle).append (New_Line);
            ouput.append("I have ").append(iPnumberofUnits).append(" units in stock.").append (New_Line);
            ouput.append("The total value of my inventory on this product is: ").append(dformat.format(stockValue())).append (New_Line);
            return ouput.toString();
        }

Is that the standard Java JLabel? 那是标准的Java JLabel吗? You are trying to pass an object of type CDinventoryItem, and the JLabel won't have a constructor to handle that kind of argument, unless it is extending the String or Icon classes. 您正在尝试传递CDinventoryItem类型的对象,并且JLabel将没有构造函数来处理这种参数,除非它扩展了String或Icon类。

  • organize your imports, so that JLabel is imported properly 整理您的导入,以便正确导入JLabel
  • JLabel does not define a constructor taking your custom type. JLabel没有定义采用您的自定义类型的构造函数。 You need to pass a string there. 您需要在此处传递一个字符串。

Just a guess, but your question wording implies you're trying to use a private field directly from a subclass? 只是一个猜测,但是您的问题用语暗示您试图直接从子类中使用私有字段吗? private fields can't be seen anywhere other than the class that they're declared in, including classes in the same inheritance hierarchy. 除了在其中声明了类的地方(包括相同继承层次结构中的类)之外,在其他任何地方都看不到私有字段。 You could make it protected, but this is frowned upon - better to either provide a mutator method to label or better still, initialise it in the superclass constructor. 您可以使它受保护,但是这是令人不满意的-最好提供一个mutator方法来标记或更好地在超类构造函数中对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM