Accessing subclass fields from a base class in Java

I have a base class called geometry, in which there is a subclass sphere:

public class Geometry 
{
 String shape_name;
 String material;

 public Geometry()
 {
     System.out.println("New geometric object created.");
 }
}

And subclasses:

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

I have an ArrayList that contains all geometry objects. I want to iterate over it to check whether the data in the text file is read correctly So far, this is my iterator method:

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 the radius and center area of the sphere? Thanks in advance:)

Solution

If you want to access the properties of a subclass, you must convert to a subclass

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

This is not the most common way of doing things: once you have more geometry subclasses, you will need to start converting to each type, which will soon become messy If you want to print the properties of an object, you should use a method called print () on the geometry object or some method along these lines, which will print each property 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();
   }
}

In this way, you do not need to convert, you only need to call g.print () in the while loop.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>