【发布时间】:2011-05-29 13:53:19
【问题描述】:
我有一个名为 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;
}
}
我有一个包含所有 Geometry 对象的 ArrayList,我想对其进行迭代以检查是否正确读取了来自文本文件的数据。到目前为止,这是我的迭代器方法:
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 的 半径和中心场? 在此先感谢:)
【问题讨论】:
-
这与stackoverflow.com/questions/2701182/… 非常相似。这能回答你的问题吗?
-
基类了解子类数据的需要指出您的抽象可能不正确。您应该退后一步,问问自己检查在做什么,是否需要在对象模型外部的实用程序类的基础、子或可能的方法上。
-
另外,您不需要“超级”。子类中的任何地方,因为它们继承了字段。
标签: java oop class inheritance subclass