Search code examples
javaclassinheritancepolymorphismabstraction

Abstract Class not initializing a parameter


I'm trying to create an abstract class SolidFigure. Both Cylinder and rectangular pirsm will inhert from it.

My problem is that the height in SolidFigure which is a common property is not initialized by the constructor (it'll be zero) whenever I instantiate either of the two classes (cylinder or rectPrism)

This is the code:

SolidFigure:

public abstract class SolidFigure {

    private double height;

    public SolidFigure(double height) {
        height = this.height;
    }

    public double getHeight() {
        return height;
    }

    protected abstract boolean isEqual(SolidFigure s);

    protected abstract double calculateVolume();
}

Cylinder:

 class Cylinder extends SolidFigure{

   private double radius;
   private static double PI = 3.14;

   public Cylinder(double height, double radius) {
       super(height);
       this.radius = radius;
   }

   @Override
   protected double calculateVolume() {
        return radius * PI * getHeight();
   }

   @Override
   protected boolean isEqual(SolidFigure s) {
       return this.calculateVolume() == s.calculateVolume();
   }
}

RectPrism:

   class RectPrism extends SolidFigure{
      private double length, width;

   public RectPrism(double height, double length, double width) {
       super(height);
       this.length = length;
       this.width = width;
   }

   @Override
   protected double calculateVolume() {
        return length * width * getHeight();
   }

   @Override
   protected boolean isEqual(SolidFigure s) {
       return this.calculateVolume() == s.calculateVolume();
   }
 }

Main:

    SolidFigure c = new Cylinder(12.0, 3);
    RectPrism r = new RectPrism(10.0, 4, 2);

    System.out.println(c.getHeight()); // This is zero
    System.out.println(r.calculateVolume()); // zero resulting from height

Solution

  • It should be the other way around

    public SolidFigure(double height) {
            this.height = height;
        }