要求在控制台输出不同的图形,定义一个父类printImage,用来绘制图形,子类打印圆形用户自定义半径,子类2打印矩形用户自定义边长
时间: 2024-05-15 12:15:39 浏览: 46
PrintBTree.zip_print_btree_二叉树 图形化_打印二叉树
以下是一个可能的实现:
```java
abstract class PrintImage {
public abstract void print();
}
class Circle extends PrintImage {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
@Override
public void print() {
int diameter = radius * 2;
for (int i = -radius; i <= radius; i++) {
for (int j = -radius; j <= radius; j++) {
int distance = (int) Math.sqrt(i * i + j * j);
if (distance <= radius) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
class Rectangle extends PrintImage {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void print() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) {
PrintImage circle = new Circle(5);
circle.print();
System.out.println();
PrintImage rectangle = new Rectangle(8, 4);
rectangle.print();
}
}
```
输出结果:
```
* * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
```
阅读全文