Search code examples
javainheritancesubclasssuperclass

Calling variable to subclass from superclass


I'm having no luck calling a variable from my superclass to my subclass. Can anyone help out?

//SUPERCLASS
public class Circle {

  protected double radius;
  protected double area;

  //Some code to construct object and initialize radius

  //Return Calculated Area
  protected double getArea() {
    area = Math.pow(radius, 2) * Math.PI;
    return area;
  }

}

//SUBCLASS
public class Cone extends Circle {

  private double height;

//Some more code with constructors and different methods

  public double getVolume() {
    {
      return (area * height / 3)
    }
  }

There is a lot more to the code but the main problem I'm having is within the subclass, the 'area' variable is 0.00 and I'm unsure how to get it equal to the 'area' that is calculated in the superclass


Solution

  • Add Constructors for both super class and sub-class like the following.

    //Super Class
    public class Circle {
    
      protected double radius;
      protected double area;
    
      public Circle(double radius) {
        this.radius = radius;
        this.area = getArea();
      }
    
      protected double getArea() {
        area = Math.pow(radius, 2) * Math.PI;
        return area;
      }
    }
    
    //Sub Class
    public class Cone extends Circle {
    
    private double height;
    
    public Cone(double radius, double height) {
        super(radius);
        this.height = height;
    }
    
    public double getVolume() {
        {
          return (area * height / 3);
        }
      }
    }
    

    After that, you can use getVolume() method of sub-class.

    public class Test {
    
      public static void main(String[] args) {
        Cone c = new Cone(3.0,5.0);
        System.out.println(c.getVolume());
      }
    }