中的基类访问子类字段

中的基类访问子类字段

本文介绍了从 Java 中的基类访问子类字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Geometry 的基类,其中存在一个子类 Sphere:

I have a base class called Geometry from which there exists a subclass 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,我想遍历它以检查是否正确读取了文本文件中的数据.到目前为止,这是我的迭代器方法:

I have an ArrayList that contains all Geometry objects and I want to iterate over it to check whether the data from a text file is read in correctly. Here is my iterator method so far:

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);
   }
  }
 }

我如何访问和打印球体的半径和中心字段?提前致谢:)

How do I access and print out the Sphere's radius and center fields?Thanks in advance :)

推荐答案

如果你想访问子类的属性,你将不得不转换到子类.

If you want to access properties of a subclass, you're going to have to cast to the subclass.

if (g instanceof Sphere)
{
    Sphere s = (Sphere) g;
    System.out.println(s.radius);
    ....
}

不过,这不是最面向对象的做事方式:一旦您拥有更多 Geometry 的子类,您将需要开始强制转换为每种类型,这很快就会变得一团糟.如果你想打印一个对象的属性,你应该在你的 Geometry 对象上有一个方法叫做 print() 或者类似的东西,它将打印对象中的每个属性.像这样:

This isn't the most OO way to do things, though: once you have more subclasses of Geometry you're going to need to start casting to each of those types, which quickly becomes a big mess. If you want to print the properties of an object, you should have a method on your Geometry object called print() or something along those lines, that will print each of the properties in the object. Something like this:


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() 即可.

This way, you don't need to do the casting and you can just call g.print() inside your while loop.

这篇关于从 Java 中的基类访问子类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 16:40