java变量在扩展另一个类的类中不可见
我有两个类:book
和video
,这两个类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弹出一个错误,即book
和video
变量不在类item
中
为什么扩展项的类中的变量不可见?如何访问这些变量
# 1 楼答案
父类无法知道其子类的字段是什么。为了获得对这些字段的正确访问,您不需要实例化
item
,而是分别实例化video
和book
,然后将它们分别添加到列表中。这也意味着不能将add
方法放在两个if
语句的末尾,因为它们需要添加到if
语句的内部因为它是一个混合的层次结构集合,所以可以编写
List<? super item> theList = new ArrayList<>();
并以这种方式添加元素# 2 楼答案
问题是
newItem
属于item
类型。虽然abook
和avideo
都是item
,但事实并非如此如果您想让编译器看到在子类中声明的变量,则需要在访问它们的变量之前将
newItem
强制转换到相应的子类。每次需要时都可以这样做,但最好是说book b = new book()
而不是item newItem = new book()