如果要访问子类的属性,则必须转换为子类。
if (g instanceof Sphere){ Sphere s = (Sphere) g; System.out.println(s.radius); ....}但是,这并不是最OO的处理方式:一旦拥有更多的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()即可。



