我有一个名为ArrayList
的{{1}},它存储了一个名为building
的超类的实例。 (此时我只定义了一个名为Residence
的子类。我想要做的是从文本文件中读取位置是Manager
,(管理员的简称)创建一个名为“mng”类型管理器的对象并将其存储在m
中。我读取文件时没有问题,但是一旦我在构造函数中插入值,值就变为空。
这是我的宿舍:
building
经理班:
public class Residence {
String posision;
String username;
String pass;
String accNo;
String type;
String no;
public Residence(String p, String u, String pas, String acc, String type, String no) {
this.posision = p;
this.username = u;
this.pass = pas;
this.accNo = acc;
this.type = type;
this.no = no;
}
public Residence() {}
}
这是主要的:
public class Manager extends Residence {
public String posision;
public String username;
public String pass;
public String accNo;
public String type;
public String no;
public Manager() {
super();
}
public Manager(String p, String u, String pas, String acc, String type, String no) {
super(p , u , pas, acc, type , no);
}
public String getUsername() {
return username;
}
}
主要的输出如下:
public static void main(String[] args) {
File file = new File("E:\\guaz\\eclipse_javafx\\workspace\\dkflozaTesting\\src\\dkflozaTesting\\danial.txt");
ArrayList<Residence> building = new ArrayList<Residence>();
String posision = "";
String username = "";
String pass = "";
String accNo = "";
String type = "";
String no = "";
try {
Scanner scan = new Scanner(file);
while(scan.hasNext()) {
posision = scan.next();
username = scan.next();
pass = scan.next();
accNo = scan.next();
type = scan.next();
no = scan.next();
System.out.println(posision + " " + username + " " + pass + " " + type + " " + no);
if (posision.compareToIgnoreCase("m") == 0) {
System.out.println("in if : " + posision + " " + username + " " + pass + " " + type + " " + no);
Manager mng = new Manager(posision, username, pass, accNo, type, no);
System.out.println("username : " + mng.getUsername());
building.add(mng);
}
}
System.out.print("\n \n");
//System.out.print(list.size());
//System.out.print(list.get(0).getUsername());
System.out.print("\n \n");
} catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
值得一提的是公寓的大小变为1,但所有属性的值都为空。
答案 0 :(得分:1)
如果要初始化变量,则必须从Manager类中删除变量。
public class Manager extends Residence {
public Manager() {
super();
}
public Manager(String p, String u, String pas, String acc, String type, String no) {
super(p , u , pas, acc, type , no);
}
public String getUsername() {
return username;
}
}
由于您已覆盖变量,因此如果要分配值,则必须重新初始化它们。但是,如果继承它们,则无法覆盖相同的变量。 (Ps.变量通常应设置为私有并使用getter和setter)