漳州专业网站建设费用中职学校专业建设方案
【案例4-1】打印不同的图形
记得 关注,收藏,评论哦,作者将持续更新。。。。
【案例介绍】
- 案例描述
 
本案例要求编写一个程序,可以根据用户要求在控制台打印出不同的图形。例如,用户自定义半径的圆形和用户自定义边长的正方形。
- 运行结果
 

【案例分析】
(1)创建父类MyPrint类,包含show()方法,用于输出图形的形状。
(2)创建子类MyPrintSquare类,重写show ()方法,用“*”打印出边长为5的正方形。
(3)创建子类MyPrintCircle类,重写show ()方法, 用“*”打印出半径为5的圆。
(4)创建测试类,设计一个myshow(MyPrint a)方法,实现输出的功能:如果为MyPrintSquare, 输出边长为5的正方形,如果为MyPrintCircle对象,输出半径为5的圆;主函数中创建MyPrintSquare、MyPrintCircle的对象,分别调用myshow,检查输出结果。
【案例实现】
MypointTest.java
- abstract class MyPoint {
 - public abstract void show();
 - }
 - //打印正方形
 - class MyPrintSquare extends MyPoint {
 - @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();
 - }
 - }
 - }
 - //打印圆形
 - class MyPrintCircle implements MyPoint{
 - @Override
 - public void show() {
 - for (int y = 0; y <= 2 * 5; y += 2) {
 - int x = (int)Math.round(5 - Math.sqrt(2 * 5 * 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('*');
 - }
 - }
 - }
 - public class MyPointTest {
 - public static void myShow(MyPoint a){
 - a.show();
 - }
 - public static void main(String[] args){
 - MyPoint mp1 = new MyPrintSquare();
 - MyPoint mp2 = new MyPrintCircle();
 - myShow(mp1);
 - myShow(mp2);
 - }
 - }
 
在上述代码中,第1~3行代码创建了一个抽象类MyPrint类,在MyPrint类中创建了一个show()方法用于输出图形的形状。然后第 21~49行代码分别创建了MyPrintSquare和MyPrintCircle类,并重写了MyPrint类的show()方法,分别用于打印正方形和圆形,最后再测试类中分别调用了MyPrintSquare和MyPrintCircle类的show()方法,打印正方形和圆形。
