Search code examples
javareturn-valueboolean-expression

JAVA return value from constructor


public class RightAngleTriangle
{
    int height;
    int width;
    double area;
    double perimeter;

    public RightAngleTriangle()
    {
        height = 1;
        width = 1;
    }

    public RightAngleTriangle(int hei, int wid)
    {
        if(hei > 0 && wid > 0)
        {
            height = hei;
            width = wid;
        }
        else
        {
            height = 1;
            width = 1;
        }
    }

    public double area()
    {
        area = height * width;
        return area;
    }

    public double perimeter()
    {
        perimeter = (height * 2) + (width * 2);
        return perimeter;
    }

    public boolean isIsosceles()
    {
        if(height == width)
        {
            return true;
        }
        return false;
    }

    public boolean largerThan(RightAngleTriangle anotherRightAngleTriangle)
    {
        if (area(RightAngleTriangle) > area(anotherRightAngleTriangle))
        {

        }
    }

}

For the method largerThan() how can I make it so largerThan() returns true if and only if the area of this RightAngleTriangle is larger than the area of anotherRightAngleTriangle. I am not sure how to compare the areas because the area is calculated locally. I tried initializing area globally but I need the returned value not the initialized value.


Solution

  • Just as a comment largerThan() is not a constructor, is a method

    now to your question

    you need to call the method in the current instance and in the object passed as parameter

    public boolean largerThan(RightAngleTriangle anotherRightAngleTriangle)
    {
        if (this.area() > anotherRightAngleTriangle.area( ))
        {
             //your logic
        }
    }
    

    or simple doing

    public boolean largerThan(RightAngleTriangle anotherRightAngleTriangle)
    {
       return this.area() > anotherRightAngleTriangle.area();
    }