访问子类的属性

时间:2019-03-11 16:56:56

标签: java inheritance iteration

我对Java还是很陌生,并且正在努力查看为什么我在命令行中总是遇到错误。我有一个超类Guest,它的变量为guestID,fName,lName和dateJoin。我还有一个带有附加变量VIPstartDate和VIPexpiryDate的VIPGuest子类。

我有一个ArrayList来宾,其中包含我记录中拥有的所有来宾对象。我想遍历ArrayList并将每个Guest写到一个文本文件中,每个Guest都以新行的形式在guestID,fName,lName,dateJoin中用逗号分隔(或guestID,fName,lName,dateJoin,VIPstartDate,VIPexpiryDate客人是VIPGuest)。

我的代码如下。当我使用类似的代码对没有子类的类的对象的ArrayList做类似的事情时,它工作正常,但是当我尝试解决某些来宾具有额外变量的事实时,错误是:

  HotelImpl.java:440: error: cannot find symbol
                    + "," + g.getVIPstartDate() + "," + g.getVIPexpiryDate());
                             ^
      symbol:   method getVIPstartDate()
      location: variable g of type Guest
    HotelImpl.java:440: error: cannot find symbol
                    + "," + g.getVIPstartDate() + "," + g.getVIPexpiryDate());
                                                         ^
      symbol:   method getVIPexpiryDate()
      location: variable g of type Guest
    2 errors

我可以看到VIPGuest对象的额外变量有问题,但是我想我可以通过if / else来解决:

  public boolean saveGuestsData(String guestsTxtFileName){
    BufferedWriter writer;
    try{
      writer = new BufferedWriter(new FileWriter(guestsTxtFileName));
    } catch (IOException e){
      System.out.print("Invalid file.");
      return false;
    }
      try{
            for (Guest g : guests){
              if (!(g instanceof VIPGuest)){
                writer.write(
                g.getGuestID() + "," + g.getFName() + "," + getLName() 
                + "," + g.getDateJoin());

              }
              else {
                writer.write(
                g.getGuestID() + "," + g.getFName() + "," + 
                getLName() + "," + g.getDateJoin() + "," + 
                g.getVIPstartDate() + "," + g.getVIPexpiryDate());
              }
              writer.newLine();

            }
          writer.close();
          return true;
          } catch (FileNotFoundException ex) {
            System.out.print("File not found.");
            return false;
          } catch (IOException e){
            System.out.print("Invalid file.");
            return false;
          }
  }

请告知?

我希望我已经正确设置了格式,但是如果我需要添加更多代码,请告诉我。谢谢:)

0 个答案:

没有答案
相关问题