我有一個名爲'Items'的類,'Equips'從'Equips'擴展而'Helmet'從'Equips'擴展。我有一個名爲'getStats'的方法,它從.txt文件加載項目的統計信息。如果我將'getStats'方法放在'Items'類中,那麼無論我嘗試使用'this'在'Helmet'對象中訪問哪個字段。顯示爲空。當頭盔在加載文本文件之前創建時,我試圖在「頭盔」中訪問的字段被初始化。我可以很容易地將'getStats'方法放在'Equips'類中,並在'Items'類中放置一個空白的'getStats'方法,但我想知道是否有辦法讓它工作。提前致謝!在java中使用'this'關鍵字擴展類
Items.java:
package com.projects.aoa;
import static com.projects.aoa.Print.*;
import java.util.*;
import java.io.*;
class Items {
String name, type;
int id;
int hp, mp, str, def;
boolean vacent;
static void getAllStats(Items[] e){
for(Items i : e){
getItemStats(i);
}
}
static void getItemStats(Items i){
i.getStats();
}
void getStats(){
try {
//System.out.println(System.getProperty("user.dir"));
print(this.name); //THIS shows up as null as well as those \/below\/
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")
+ "/src/com/projects/aoa/" + this.type + this.name + ".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
int counter = 0;
while ((line = br.readLine()) != null) {
if (line.length() == 0){
break;
}
switch (counter) {
case 0:
this.hp = Integer.parseInt(line);
counter++;
break;
case 1:
this.mp = Integer.parseInt(line);
counter++;
break;
case 2:
this.def = Integer.parseInt(line);
counter++;
break;
case 3:
this.str = Integer.parseInt(line);
counter++;
break;
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Game.java:
Helmet headBand = new Helmet("HeadBand");
Helmet bronzeHelmet = new Helmet("BronzeHelmet");
Items[] equips = {
headBand, bronzeHelmet
};
getAllStats(equips);
Equips.java:
package com.projects.aoa;
import static com.projects.aoa.Print.print;
import static com.projects.aoa.Print.println;
import java.io.*;
class Equips extends Items{
String name, type;
int hp, mp, str, def;
void printStats(){
println("[" + name + "]");
println("Type: " + type);
println("HP: " + hp);
println("MP: " + mp);
println("Def: " + def);
println("Str: " + str);
}
}
class Helmet extends Equips {
Helmet(String name){
this.name = name;
this.type = "h_";
}
}
你能向我們展示一些'Helmet'的代碼嗎?我懷疑'Helmet'類也有'name'參數,否則你只是忘了設置'name'。 – Bringer128