本案例要求使用抽象类知识编写一个程序,可以根据用户要求在控制台打印出不同的图形。例如,用户自定义半径的圆形和用户自定义边长的正方形。
此案例有四个类
MyPrint,MyPrintCircle, MyPrintSquare,Test
Myprint类
public abstract class MyPrint {
public abstract void show();
}
Myprintcircle(圆形)类
public class MyPrintCircle extends MyPrint {
@Override
public void show() {
//打印圆形
for (int y = 0; y <= 10; y +=2) {
int x =(int)Math.round(5-Math.sqrt(10*y-y*y));
int len =2*(5-x);
for (int i = 0; i <= x; i++) {
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j <= len; j++) {
System.out.print(" ");
}
System.out.println("*");
}
}
}
Myprintsquare(长方形)类
public class MyPrintSquare extends MyPrint {
@Override
public void show() {
//打印正方形
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j==0||j==4){
System.out.print("*");
}else if (i==0||i==4){
System.out.print("*");
}else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Test类
public class Test {
public static void main(String[] args) {
useMyPrint(new MyPrintSquare());
useMyPrint(new MyPrintCircle());
}
public static void useMyPrint(MyPrint my) {
my.show();
}
}
结果展示