0

With no working example, my text book leaves me on my own to figure this out. How would I go about trying to create a programmer defined class. It would make two Rectangle objects and find their area and perimeter. I already have those functions complete however, i'm currently trying set up the set and get methods. I need to use public set methods to set values for length and width then use public get methods to retrieve the values for length and width.

class Rectangle {
    // Length of this rectangle.
    private double length;
    // Width of this rectangle.
    private double width;
    // Write set methods here.
    public void setLength() {
        length = 10;
    }
    public void setWidth() {
        width = 5;
    }
    // Write get methods here.
    public double getLength() {
        return length;
    }
    public double getWidth() {
        return width;
    }
    // Write the calculatePerimeter() and
    public double calculatePerimeter() {
        return( (length * 2) + (width * 2) );
    }
    // calculateArea() methods here.
    public double calculateArea() {
        return( length * width );
    }
}

Any help would be greatly appreciated.

JohnH
  • 17
  • 6

2 Answers2

0

You're pretty much done, except your setters are actually not setting anything at all. By convention, setFoo (where foo is the name of a field) accepts a parameter of a matching type.

In your case, you'd want setLength and setWidth to read as thus:

public void setLength(final double length) {
    // actual implementation = exercise for reader
}

public void setWidth(final double width) {
    // actual implementation = exercise for reader
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
0

The way to builder setters is to have the same type as param, and assign it to the attribut :

public void setLength(double l) {
    length = l;
}
public void setWidth(double w) {
    width = w;
}
azro
  • 53,056
  • 7
  • 34
  • 70