I'm working on a school project where I need to extend Java's default Rectangle
class into a subclass called MyRectangle
; the subclass has additional variables including width
and height
, and when I use a dot operator to print those values out I get the correct numbers in the output. However, when I try to do the same with the x
and y
values of my MyRectangle
objects I always end up getting the default x
and y
values (0 and 0) even when I pass different values through parameters in my constructors. I thought that maybe renaming the parameters in my subclass' constructors and then assigning those new parameter's values to the superclass' x
and y
variables would fix the issue, but it only led to errors.
The desired outputs (with respect to x
and y
) would be:
x = 0 y = 0 // x = 5 y = 5 // x = 0 y = 0 // x = -10 y = 3
Any help would be greatly appreciated! Here's my code:
class Main {
public static void main(String[] args) {
MyRectangle mr1 = new MyRectangle(0, 0, 4, 2, "blue", "red", true);
MyRectangle mr2 = new MyRectangle(5, 5, 10, 3, "green");
MyRectangle mr3 = new MyRectangle();
MyRectangle mr4 = new MyRectangle(-10, 3, 10, 3, mr2.color);
System.out.println( "x = " + mr1.x + " y = " + mr1.y + " width = " + mr1.width + " height = " + mr1.height + " color = " + mr1.color +" area = " + mr1.area() + " perimeter = " + mr1.perimeter()); //Prints info about mr1
System.out.println( "x = " + mr2.x + " y = " + mr2.y + " width = " + mr2.width + " height = " + mr2.height + " color = " + mr2.color + " borderColor = " + mr2.borderColor + " area = " + mr2.area() + " perimeter = " + mr2.perimeter()); //mr2
System.out.println( "x = " + mr3.x + " y = " + mr3.y + " width = " + mr3.width + " height = " + mr3.height + " color = " + mr3.color + " borderColor = " + mr3.borderColor + " area = " + mr3.area() + " perimeter = " + mr3.perimeter()); //mr3
System.out.println( "x = " + mr4.x + " y = " + mr4.y + " width = " + mr4.width + " height = " + mr4.height + " color = " + mr4.color + " borderColor = " + mr4.borderColor + " area = " + mr4.area() + " perimeter = " + mr4.perimeter()); //mr4 }
public static class MyRectangle extends Rectangle {
public int width, height;
public String color, borderColor;
public boolean border;
//MyRectangle has 3 constructors
public MyRectangle() {
super();
width = height = 1;
}
public MyRectangle(int x, int y, int w, int h, String c) {
super(x,y);
width = w;
height = h;
color = c;
}
public MyRectangle(int x, int y, int w, int h, String c, String bc, boolean b) {
this(x,y,w,h,c);
borderColor = bc;
border = b;
}