用JAVA实现,改写矩形类,使之实现Printable接口,用printItMyWay()方法将矩形的相关信息(长、宽、周长、面积)打印在屏幕上;改写正方形类,重载 printItMyWay()方法将正方形的相关信息(边长、周长、面积)打印在屏幕上。
时间: 2024-05-10 15:20:20 浏览: 75
矩形类实现Printable接口:
```java
public class Rectangle implements Printable {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public double getArea() {
return length * width;
}
@Override
public void printItMyWay() {
System.out.println("矩形长为:" + length);
System.out.println("矩形宽为:" + width);
System.out.println("矩形周长为:" + getPerimeter());
System.out.println("矩形面积为:" + getArea());
}
}
```
正方形类重载printItMyWay()方法:
```java
public class Square extends Rectangle {
public Square(double side) {
super(side, side);
}
public double getSide() {
return getLength();
}
public void setSide(double side) {
setLength(side);
setWidth(side);
}
@Override
public void printItMyWay() {
System.out.println("正方形边长为:" + getSide());
System.out.println("正方形周长为:" + getPerimeter());
System.out.println("正方形面积为:" + getArea());
}
}
```
使用:
```java
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(3, 4);
rectangle.printItMyWay();
Square square = new Square(5);
square.printItMyWay();
}
```
输出:
```
矩形长为:3.0
矩形宽为:4.0
矩形周长为:14.0
矩形面积为:12.0
正方形边长为:5.0
正方形周长为:20.0
正方形面积为:25.0
```
阅读全文