Skip to content
Advertisement

Pass calculated values by inherited classes to main class

So in my main function I got a class named Figure

Circle and Rectangle extend class Figure. Square extends class Rectangle.

Now I have to print the values from created objects. I think I am approaching this in wrong way. How can I pass the values to the print function that have been created by other classes?

public class Figure { 
  private double area;
  private double perimeter;
  private String name;

  public Figure() { 
    this.area = 0.0;
    this.perimeter = 0.0;
    this.name = "";
  }

   public void print() {
        System.out.println(this.area + this.perimeter + this.name);
    }
     public static void main(String args[]) {

      Figure[] figureList = new Figure[5];
        figureList[0] = new Circle(5);
        figureList[1] = new Square(5);
        figureList[2] = new Rectangle(5, 9);

        for(int i=0;i<3;i++) {
         System.out.println(figureList[i].print()); // wont print anything
        }
     }
}
public class Circle extends Figure {
    private double radius;
    
    public Circle(double a) {
        this.radius= a;

        this.calcPerimeter();
        this.calcArea();
    }

    public double calcPerimeter(){
        return 2*(Math.PI*this.radius);
    }
    public double calcArea(){
        return Math.PI*(this.radius*this.radius);
    }
    public void increase(int a){
        this.radius*=a;
        this.calcArea();
    }

    
}

Should I not be using return in the calcPerimeter and calcArea methods? Because I need to pass this somehow to Figure class. Also I have same as above class for rectangle.

And this class that extends rectangle.

public class Square extends Rectangle {
    private double sideA;

    public Square(double a) {
        this.sideA = a;

        this.calcPerimeter();
        this.calcArea();
    }

    public double calcArea() {
        return (this.sideA*this.sideA);
    }

    public double calcPerimeter() {
        return 4*this.sideA;
    }
}

Can someone advice me how to do it properly, I just started my journey with Java and Im practicing on objects.

Advertisement

Answer

Firstly, you have made all 3 members of Figure class as private, so if you want the base classes to update them, then make them protected, and use super.area, super.perimeter, etc. to update them.

Yes you dont need to return but update parent’s values using the super keyword.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement