Search code examples
javagetter-setter

Java getters and setters not working


I am doing a homework assignment where I determine the volume of a cylinder. The object of the lesson is Classes and Objects. I have two classes, "CylinderTest" & "Cylinder". Cylinder test calls Cylinder. Everything seems to be working so far except the get and set methods. I am trying to prevent calculations on a negative number, but this is not working, it performs the calculations regardless.

Here is the CylinderTest class

public class CylinderTest
{

    public static void main(String[] args)
    {
        Cylinder myTest = new Cylinder(-1, -1);
        myTest.getHeight();
        myTest.getRadius();
        System.out.println(myTest);

        printHeader();
        double volume = myTest.volume();
        displayCylinder(volume);
    }

    private static void printHeader()
    {
        System.out.println("Cylinder");
        System.out.println("________");
    }

    private static void displayCylinder(double volume)
    {
        System.out.print("Cylinder volume = ");
        System.out.println(volume);
    }
}

Here is the Cylinder class

public class Cylinder
{
    // variables
    public static final double PI = 3.14159;
    private double radius, height, volume;

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

    // Volume method to compute the volume of the cylinder
    public double volume()
    {
        return PI * radius * radius * height;
    }

    // accessors and mutators (getters and setters)
    public double getRadius()
    {
        return radius;
    }

    public void setRadius(double radius)
    {
        if (radius > 0.0)
            this.radius = radius;
        else
            this.radius = 1.0;
    }

    public double getHeight()
    {
        return height;
    }

    public void setHeight(double height)
    {
        if (height > 0.0)
            this.height = height;
        else
            this.height = 1.0;
    }

    public double getVolume()
    {
        return volume;
    }

    public void setVolume(double volume)
    {
        this.volume = volume;
    }

}

Solution

  • Your constructor should call your setters, and you should check your logic in the setters. Do you really want to carry on with the value of 1 if the calling code passes a negative value?