所以我有一个对象的ArrayList。这些对象内部有各种属性及其值。
代码非常简单。 GBox 和 GCircle 是 GHP 的子级。 ArrayList 在 World 中。
我想要做的是打印盒子的 HP 和体积以及圆的 HP 和直径。我知道我可以重写 toString() 但我实际上想获取这些值。这样做的正确语法是什么?
//Main.java
public class Main {
public static void main(String[] args) {
Ini i = new Ini();
}
}
//Ini.java
public class Ini {
private static World w;
public Ini() {
w = new World;
w.makeGBox();
w.makeGCircle();
System.out.println("Box: HP: " +
w.getList().get(0).getHP() +
"Volume: " +
w.getList().get(0).GBox.getVolume());
//compile error no variable GBox in GHP
System.out.println("Circle: HP: " +
w.getList().get(1).getHP() +
"Radius: " +
w.getList().get(1).GCircle.getRadius());
//compile error no variable GCircle in GHP
}
}
//World.java
import java.util.ArrayList;
public class World {
private ArrayList<GHP> list = new ArrayList<>();
public void makeGBox() {
list.add(new GBox());
}
public void makeGCircle() {
list.add(new GCircle());
}
public ArrayList<GHP> getList() {
return list;
}
}
//GHP.java
public class GHP {
private int HP;
public GHP() {
setHP(5);
}
public int getHP() {
return HP;
}
public void setHP(int HP) {
this.HP = HP;
}
}
//GBox.java
public class GBox extends GHP{
private int volume;
public GBox() {
setVolume(10);
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
//GCircle.java
public class GCircle extends GHP{
private int radius;
public GCircle {
setRadius(7);
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
最佳答案
除了许多编译问题之外,您还需要进行这些更改才能实现您想要的效果。
for (GHP ghp : w.getList()) { // Avoid using get(index) without a forloop, as such
if (ghp instanceof GBox) { // Using the instanceof operator, you can differentiate the 2 class types
System.out.println("Box: HP: " + ghp.getHP() + "Volume: "
+ ((GBox) ghp).getVolume()); // Cast it to GBox to be able to call getVolume
}
if (ghp instanceof GCircle) {
System.out.println("Circle: HP: " + ghp.getHP() + "Radius: "
+ ((GCircle) ghp).getRadius());// Cast it to GCircle to be able to call getRadius
}
}
关于Java:当涉及父/子时,如何获取 ArrayList 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175918/