有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java变量在扩展另一个类的类中不可见

我有两个类:bookvideo,这两个类extend item

class item {
    int item_num;
    String title;
}
class video extends item {
    double length;
    char rating;
}
class book extends item {
    String author;
    int year;
}

我有一个值的文本文件,需要插入到item列表中。该文本文件如下所示:

v    382    Armageddon    120    P
v    281    Scream    138    R
b    389    Othello    Shakespeare    1603
v    101    Cellular    110    P
b    482    Hatchet    Paulson    1987

以及如何读取文件:

list<item> theList;
item newItem;
while(true) {
    if(file.isEOF) { break; }
    if(file.getChar == 'v') {
        newItem = new video();
        /* the get___ methods below grab the next value
         * in the file. Values tab delimited */
        newItem.item_num = file.getInt();
        newItem.title = file.getString();
        newItem.length = file.getDouble();
        newItem.rating = file.getChar();
    } else if (file.getChar == 'b') {
        newItem = new book();
        newItem.item_num = file.getInt();
        newItem.title = file.getString();
        newItem.author = file.getString();
        newItem.year = file.getInt();
    }
    theList.add(newItem);
}

Netbeans弹出一个错误,即bookvideo变量不在类item

为什么扩展项的类中的变量不可见?如何访问这些变量


共 (2) 个答案

  1. # 1 楼答案

    父类无法知道其子类的字段是什么。为了获得对这些字段的正确访问,您不需要实例化item,而是分别实例化videobook,然后将它们分别添加到列表中。这也意味着不能将add方法放在两个if语句的末尾,因为它们需要添加到if语句的内部

    因为它是一个混合的层次结构集合,所以可以编写List<? super item> theList = new ArrayList<>();并以这种方式添加元素

  2. # 2 楼答案

    问题是newItem属于item类型。虽然a book和a video都是item,但事实并非如此

    如果您想让编译器看到在子类中声明的变量,则需要在访问它们的变量之前将newItem强制转换到相应的子类。每次需要时都可以这样做,但最好是说book b = new book()而不是item newItem = new book()