package chapter4.demo45; /** * 图形计算器类 * 1. final 类:防止被继承 * 2. 私有构造函数(不可被实例化) * 只有静态方法,不需要实例化,所有方法都可以通过类名调用 */ public final class ShapeCalculate { private ShapeCalculate() { throw new AssertionError("不应该被实例化"); } // 打印图形面积 public static void printArea(Shape shape) { if (shape instanceof Rectangle) { System.out.println("正方形面积:"+shape.getArea()); } else if (shape instanceof Circle) { System.out.println("圆形面积:"+shape.getArea()); } else { System.out.println("未知图形面积:" + shape.getArea()); } } // 打印图形周长 // public static void printPerimeter(Shape shape) { // if (shape instanceof Rectangle) { // System.out.print("长方形"); // } else if (shape instanceof Circle) { // System.out.print("圆形"); // } else { // System.out.print("未知图形"); // } // System.out.println("周长:"+shape.getPerimeter()); // } public static void printPerimeter(Circle circle) { System.out.println("圆形周长:"+circle.getPerimeter()); } public static void printPerimeter(Rectangle rectangle) { System.out.println("长方形周长:"+rectangle.getPerimeter()); } // 打印计算器菜单 public static void printMenu() { System.out.println("==========图形计算器=========="); System.out.println("1.圆形"); System.out.println("2.长方形"); System.out.print("请输入序号选择功能:"); } }