从Java中的基类访问子类字段
发布时间:2020-12-15 05:05:23 所属栏目:Java 来源:网络整理
导读:我有一个名为Geometry的基类,其中存在一个子类Sphere: public class Geometry { String shape_name; String material; public Geometry() { System.out.println("New geometric object created."); }} 和子类: public class Sphere extends Geometry{ Vect
我有一个名为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); } } } 如何访问和打印球体的半径和中心区域? 解决方法
如果要访问子类的属性,则必须转换为子类.
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()即可. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |