diff --git "a/06 \346\236\227\346\231\237\350\276\211/20230506 \345\244\232\346\200\201\344\275\234\344\270\232.md" "b/06 \346\236\227\346\231\237\350\276\211/20230506 \345\244\232\346\200\201\344\275\234\344\270\232.md" new file mode 100644 index 0000000000000000000000000000000000000000..424212e354b518273e903b1aec92579a85161349 --- /dev/null +++ "b/06 \346\236\227\346\231\237\350\276\211/20230506 \345\244\232\346\200\201\344\275\234\344\270\232.md" @@ -0,0 +1,154 @@ +## 多态练习 + +### 1、图形 + +(1)父类Graphic图形 + +- public double area()方法:返回0.0 +- public double perimeter()方法:返回0.0 +- public String getInfo()方法,返回图形面积和图形周长 + +(2)子类Circle圆继承Graphic图形 + +- 包含属性:radius,属性私有化 +- 包含get/set方法 +- 重写area()求面积方法 +- 重写perimeter()求周长方法 +- 重写getInfo()方法,返回圆的半径,面积和周长 + +(3)子类矩形Rectangle继承Graphic图形 + +- 包含属性:length、width,属性私有化 +- 包含get/set方法 +- 重写area()求面积方法 +- 重写perimeter()求周长方法 +- 重写getInfo()方法,返回长和宽,面积、周长信息 + +(4)在测试类中,新建一个比较图形面积的方法,再建一个比较图形周长的方法,main方法中创建多个圆和矩形对象,再调用方法比较他们的周长或面积。 + +```Java +package D1; + +public class Graphic { + public double area(){ + return 0.0; + } + public double perimeter(){ + return 0.0; + } + public String getInfo(){ + String a="面积是:"+area()+",周长是:"+perimeter(); + return a; + } +} +class Circle extends Graphic{ + private double radius; + + public Circle(double radius) { + this.radius = radius; + } + + public Circle() { + } + + public double getRadius() { + return radius; + } + + public void setRadius(double radius) { + this.radius = radius; + } + + @Override + public double area() { + double area=Math.PI*(radius*2); + return area; + } + + @Override + public double perimeter() { + double perimeter=2*radius*Math.PI; + return perimeter; + } + + @Override + public String getInfo() { + return "半径是"+radius+"面积是:"+area()+",周长是:"+perimeter(); + } +} +class Rectangle extends Graphic{ + private double length; + private double width; + + public Rectangle(double length, double width) { + this.length = length; + this.width = width; + } + + public Rectangle() { + } + + public double getLength() { + return length; + } + + public void setLength(double length) { + this.length = length; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + @Override + public double area() { + return length*width; + } + + @Override + public double perimeter() { + return (length+width)*2; + } + + @Override + public String getInfo() { + return "长是:"+length+"宽是:"+width+"面积是:"+area()+",周长是:"+perimeter(); + } +} +class Test { + public static void main(String[] args) { + Graphic gr = new Circle(3.14); + Graphic re = new Rectangle(3.14, 2.5); + area(gr,re); + perimeter(gr,re); + } + + + + static void area(Graphic a,Graphic b){ + if (a.area()>b.area()){ + System.out.println("第一个图形面积比第二个大"); + } else if (a.area()b.area()){ + System.out.println("第一个图形周长比第二个长"); + } else if (a.area()