我有一个名为的基类Geometry其中存在一个子类Sphere:
public class Geometry
{
String shape_name;
String material;
public Geometry()
{
System.out.println("New geometric object created.");
}
}
和一个子类:
public class Sphere extends Geometry
{
Vector3d center;
double radius;
public Sphere(Vector3d coords, double radius, String sphere_name, String material)
{
this.center = coords;
this.radius = radius;
super.shape_name = sphere_name;
super.material = material;
}
}
我有一个包含所有内容的 ArrayListGeometry对象,我想迭代它以检查文本文件中的数据是否正确读取。到目前为止,这是我的迭代器方法:
public static void check()
{
Iterator<Geometry> e = objects.iterator();
while (e.hasNext())
{
Geometry g = (Geometry) e.next();
if (g instanceof Sphere)
{
System.out.println(g.shape_name);
System.out.println(g.material);
}
}
}
我如何访问并打印Sphere's半径和中心场?
提前致谢 :)
如果您想访问子类的属性,则必须强制转换为子类。
if (g instanceof Sphere)
{
Sphere s = (Sphere) g;
System.out.println(s.radius);
....
}
不过,这并不是最面向对象的做事方式:一旦您拥有更多 Geometry 子类,您将需要开始转换为每种类型,这很快就会变得一团糟。如果要打印对象的属性,您应该在 Geometry 对象上有一个名为 print() 的方法或类似的方法,它将打印对象中的每个属性。像这样的事情:
class Geometry {
...
public void print() {
System.out.println(shape_name);
System.out.println(material);
}
}
class Shape extends Geometry {
...
public void print() {
System.out.println(radius);
System.out.println(center);
super.print();
}
}
这样,您不需要进行转换,只需在 while 循环内调用 g.print() 即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)