package com.eclipse.chancewalker;
public class rectangleCW {
private static double width;
private static double height;
public rectangleCW() {
width = 1;
height = 1;
}
public rectangleCW(double w, double h) {
width = w;
height = h;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return width + height + width + height;
}
}
package com.eclipse.chancewalker;
public class rectangleTestCW {
public static void main(String[] args) {
rectangleCW r1 = new rectangleCW(4, 40);
rectangleCW r2 = new rectangleCW(3.5, 35.9);
System.out.println("The height for rectangle 1 is: " + 40);
System.out.println("The width for rectangle 1 is: " + 4);
System.out.println("The area for rectangle 1 is: " + r1.getArea());
System.out.println("The perimeter for rectangle 1 is: " + r1.getPerimeter());
System.out.println("The height for rectangle 2 is: " + 359);
System.out.println("The width for rectangle 2 is: " + 3.5);
System.out.println("The area for rectangle 2 is: " + r2.getArea());
System.out.println("The perimeter for rectangle 2 is: " + r2.getPerimeter());
}
}
Top comments (5)
You'll likely want to remove static from the two instance variables.
Static
basically makes them stick to all rectangles, rather than being unique to each one. When you change thewidth
orheight
, because they're static, the width of all rectangles changes. More information on that is available here.I tried it this was the result:
Error: Main method is not static in class com.eclipse.chancewalker.rectangleTestCW, please define the main method as:
public static void main(String[] args)
But I did need to delete the static for the private double's, so thank you so much for the help!
The main method needs to remain as static, as per how Java defines programs. The instance variables (
width
, andheight
) are the ones that should not be static. Instance variables are variables that belong of specific occurrences, or "instances," of a class. Each rectangle should have its own length and width, and shouldn't care about what any other rectangle does. That's how variables work without thestatic
keyword, and these are called instance variables.If you were to keep track of how many rectangles existed, it would make sense to have a
private static int count
variable that didn't need to be different for each rectangle. Static links the variable to the class rather than one instance.The
main()
method signature should look like this, as always:Best of luck on your work!
public class RectangleCW {
private double width;
private double height;
}
public class RectangleTestCW {
public static void main(String[] args) {
}
System.out.println("The height for rectangle 1 is: " + 40);
System.out.println("The width for rectangle 1 is: " + 4);
System.out.println("The height for rectangle 2 is: " + 359);
System.out.println("The width for rectangle 2 is: " + 3.5);
add some getters for these
hardcoding values won't help you much a bigger problem