【问题标题】:Super & Sub Classes超类和子类
【发布时间】:2013-12-02 19:44:10
【问题描述】:
  1. 这是我的应用程序类,我有对象数组

  2. loanBook 是一个超类,loanDocumentry 是一个继承自loanBook 的子类。这是在应用程序类的顶部声明的

    public static loanBook[] bookArray = new loanDocumetry[5];

然后在我的应用程序类中,我必须添加新的文档书,所以我使用扫描仪进行输入,然后使用它们添加新对象

bookArray[i] = new loanDocumentry(
    title, author, publisher, year, noOfPages, genre);

并且loanBook 中的书籍数量增加了,所以我知道每次运行它都会创建新书籍的方法,但是当打印出数组时,它看起来好像从未将这些书籍中的任何一本添加到数组中,并且只有一本我添加的是最后一个

应用类:

public class ApplicationClass {

public static Scanner input = new Scanner(System.in);
public static loanBook[] bookArray = new loanDocumentry[5];

public static void main(String[] args) {
    addBook();
}

public static void addBook() {
    input.nextLine();

    String title;
    String author;
    String publisher;
    int year;
    int noOfPages;
    String genre;
    String choice;
    int i = 0;


            System.out.print("\nTITLE of the book: ");
            title = input.nextLine();
            System.out.print("AUTHOR of the book: ");
            author = input.nextLine();
            System.out.print("PUBLISHER of the book: ");
            publisher = input.nextLine();
            System.out.print("YEAR book was published in: ");
            year = input.nextInt();
            System.out.print("NUMBER OF PAGES the book has: ");
            noOfPages = input.nextInt();
            System.out.print("GENRE of the book: ");
            input.nextLine();
            genre = input.nextLine();
            bookArray[i] = new loanDocuemntry(title, author, publisher, year, noOfPages, genre);
            i++;

}

loanBook 超类和loanDocumentry 子类都使用set 和gets

【问题讨论】:

  • 为什么不评论你所做的事情,而是发布你的代码?
  • 它的代码很长,有 4 个不同的 java 文件,它的菜单驱动有很多打印语句等
  • 相关材料:stackoverflow.com/questions/12878879/… 也尝试从声明中删除静态。
  • 尝试创建SSCCE,然后您将问题隔离出来,如果您仍然需要帮助,这对您和我们来说都会更容易。

标签: java inheritance subclass


【解决方案1】:

尝试从bookArray[i] = new loanDocumenry( 上方的行中打印i 在添加每个新的 loanBook 时,它应该会发生变化。

当你添加一个loanBook时,i应该增加1,所以你设置bookArray[0]bookArray[1]bookArray[2]bookArray[3]bookArray[4]。您只设置了第一个。

【讨论】:

  • 加一
  • 是的,在您的方法中,您将其设置为 0。然后在最后将其增加到 1。但是,当您添加下一本书时,它再次从 0 开始,然后再次增加到 1。向方法添加静态不会使 int i 保持与之前相同的值。
  • 我该如何修改这个?
  • 如果我有我的方法之外会有帮助
  • 最简单的方法是将i 移到该方法可以访问它的方法上方的某个位置。
猜你喜欢
  • 2014-03-23
  • 1970-01-01
  • 2013-02-25
  • 2014-08-12
  • 2016-04-04
  • 2012-11-09
  • 1970-01-01
相关资源
最近更新 更多