Access subclass fields from a base class in Java

后端 未结 4 1464
暖寄归人
暖寄归人 2020-12-02 01:14

I have a base class called Geometry from which there exists a subclass Sphere:

public class Geometry 
{
 String shape_name;
 String materia         


        
4条回答
  •  自闭症患者
    2020-12-02 01:31

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

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

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

提交回复
热议问题