Inheritance of Square method in java
I have a class Rectangle laid out like this:
package Inheritance;
/**
*
* @author Jacob
*/
public class Rectangle {
final private int length;
final private int width;
public Rectangle (int l, int w)
{
length = l;
width = w;
}
public int getLength ()
{
return length;
}
public int getWidth ()
{
return width;
}
@Override
public String toString ()
{
return String.format ("Rectangle (%dX%d)", length, width);
}
}
I then need to create class square in the following way:
ad Square: Square extends Rectangle / No fields are declared in class Square / It has a parameterized constructor with (only) one parameter / The parameter is used to initialize both fields of Rectangle / It has a method called getSide to expose the side-length of the square / Override the toString method so that it will return a String of the following form: / Square(side) eg Square(4)
The values for the sides are going to be hard coded. Rectangle is going to have a width of 4. In order to get the side of the square to be 4 do I create an instance of rectangle and call the method getWidth and set that as the side length. Thats how I would think to do it but in that case I would only be using one of the fields so, My question is how do I initialize both fields? Can I call Rectangle and make length and width equal or is there some other way I should do it?
Here is the code for my Square class:
public class Square {
public Square (int side)
{
super(side, side);
}
public int getSide ()
{
return side;
}
@Override
public String toString ()
{
return String.format ("Square (%d)", side);
}
}
For the line super(side, side) I get the error constructor Object in class Object cannot be applied to given types. Required no arguments, found int, int. For my return statements I get that it cannot find the variable side.
The values for the sides are going to be hard coded.
I assume that you mean that you will hardcode the values for the width and length when you create a Rectangle
and Square
object (for example in main()
). These values should absolutely not be hardcoded any where in the Rectangle
and Square
classes.
Rectangle is going to have a width of 4. In order to get the side of the square to be 4 do I create an instance of rectangle and call the method getWidth and set that as the side length.
Not at all. Rather, Square
should have its own constructor which calls the Rectangle
constructor with the same value for both the width
and length
:
public Square(int side) {
super(side, side); // Set the width and length to the same value.
}
链接地址: http://www.djcxy.com/p/83252.html
上一篇: 抽象类和通用代码
下一篇: java中Square方法的继承