package TcmStudy.day22; // 图形类 class Graphic{ private String name; // 不使用无参数的构造方法 使用有参数的构造方法 public Graphic(String name){ super(); //父类初始化 object基类 所有类的祖先 this.name = name; } public void setName(String name) {this.name = name;} public String getName() {return name;} // 获取面积的方法 每一个图形计算的方法 都不一样 需要重载overload public double getArea() {return 0.0;} public double getPerimeter() {return 0.0;} public String getInfo(){ // 获取图形信息 return "图形名字:" + name + ",面积:" + getArea() + ", 周长:" + getPerimeter(); } } //圆类 继承 图形类 class Circle extends Graphic{ private double radius; public Circle(String name,double radius){ super(name); // 调用父类的有参数构造方法 this.radius = radius; } public void setRadius(double radius) {this.radius = radius;} public double getRadius() {return radius;} public double getArea(){ // 重载父类的方法 获取面积 return Math.PI*radius*radius; } public double getPerimeter(){ // 获取周长 return 2*Math.PI*radius; } public String getInfo(){ // 获取圆形类的 信息 return super.getInfo() + ",半径:" + radius; } } // 长方形类 继承 图形类 class Rectangle extends Graphic{ private int length; private int width; public Rectangle(String name,int length,int width){ super(name); // 调用父类的有参数构造方法 this.length = length; this.width = width; } public void setLength(int length) {this.length = length;} public int getLength() {return length;} public void setWidth(int width) {this.width = width;} public int getWidth() {return width;} public double getArea(){ // 重载父类的方法 获取面积 return length * width; } public double getPerimeter(){ // 获取周长 return (length * width) * 2; } public String getInfo(){ return super.getInfo() + ",长度:" + length + ",宽度:" + width; } } public class TestGraphicDemo02 { public static void main(String[] args) { Circle c = new Circle("圆形", 2.5); System.out.println(c.getInfo()); Rectangle r = new Rectangle("长方形",3,4); System.out.println(r.getInfo()); } }
【继承】图形类的继承。(长方形,圆形)
最新推荐文章于 2023-11-13 20:45:00 发布