//通过程序设计几何图形(Shape)、矩形(Rectangle)、圆形(Circle)、正方形(Square)几种类型,能够利用接口和多态性计算几何图形的面积和周长并显示。
interface Shape {//声明接口Shape
final float PI = 3.14f; // 定义常量圆周率
abstract void area();//定义抽象方法面积
abstract void perimeter();//定义抽象方法周长
}
class Graphics {
double width;// 定义变量宽
double length;// 定义变量长
double radius; // 定义变量半径
double m;// 定义变量面积
double C;// 定义变量周长

public Graphics(double width, double length, double radius) {
this.width = width;
this.length = length;
this.radius = radius;
}
}
class Rectangle extends Graphics implements Shape {//实现接口
public Rectangle(double width, double length, double radius) {
super(width, length, radius);
}
public void area() {
m = width * length;
System.out.println("矩形面积:" + m);// 输出
}
    public void perimeter() {
C = (width + length) * 2;
System.out.println("矩形周长:" + C);// 输出
}
}

class Circle extends Graphics implements Shape {//实现接口
public Circle(double width, double length, double radius) {
super(width, length, radius);
}
public void area() {
m = PI * radius * radius;
System.out.println("圆形面积:" + m);// 输出
}
public void perimeter() {
C = 2 * PI * radius;
System.out.println("圆形周长:" + C);// 输出
}
}

class Square extends Graphics implements Shape {//实现接口
public Square(double width, double length, double radius) {
super(width, length, radius);
}
public void area() {
m = width * width;
System.out.println("正方形面积:" + m);// 输出
}
public void perimeter() {
C = (width + width) * 2;
System.out.println("正方形周长:" + C);// 输出


}
}
       public class Graphics1 {


public static void main(String[] args) {
Shape p1;//声明接口变量
p1 = new Rectangle(4.0, 5.0, 0);//实现类对象赋值接口变量
p1.area();//接口回调
p1.perimeter();//接口回调
p1 = new Circle(0, 0, 2.0);//实现类对象赋值接口变量
p1.area();
p1.perimeter();
p1 = new Square(3.0, 0, 0);//实现类对象赋值接口变量
p1.area();
p1.perimeter();
}

}

通过程序设计几何图形(Shape)、矩形(Rectangle)、圆形(Circle)、正方形(Square)几种类型, 能够利用接口和多态性计算几何图形的面积和周长并显示。通过程序设计几何图形(Shape)、矩形(Rectangle)、圆形(Circle)、正方形(Square)几种类型, 能够利用接口和多态性计算几何图形的面积和周长并显示。通过程序设计几何图形(Shape)、矩形(Rectangle)、圆形(Circle)、正方形(Square)几种类型, 能够利用接口和多态性计算几何图形的面积和周长并显示。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2022-12-23
  • 2022-01-18
  • 2021-05-25
  • 2021-08-25
  • 2021-11-23
猜你喜欢
  • 2022-12-23
  • 2021-10-11
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案