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

该程序设计了接口Shape,包含矩形(Rectangle)、圆形(Circle)和正方形(Square)三种类型的几何图形,并实现了计算面积和周长的功能。通过接口和多态性,可以灵活地计算不同形状的面积和周长并进行显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

interface Shape {//声明接口Shape
	final float PI = 3.14f; // 定义常量圆周率
	abstract void area();//定义抽象方法面积
	abstract void perimeter();//定义抽象方法周长
}


class bian {
	double width;// 定义变量宽
	double length;// 定义变量长
	double radius; // 定义变量半径
	double S;// 定义变量面积
	double C;// 定义变量周长


	public bian(double width, double length, double radius) {
		this.width = width;
		this.length = length;
		this.radius = radius;
	}
}


class Rectangle extends bian implements Shape {//实现接口
	public Rectangle(double width, double length, double radius) {
		super(width, length, radius);
	}


	public void area() {
		S = width * length;
		System.out.println("矩形面积:" + S);// 输出
	}


	public void perimeter() {
		C = (width + length) * 2;
		System.out.println("矩形周长:" + C);// 输出
	}
}


class Circle extends bian implements Shape {//实现接口
	public Circle(double width, double length, double ra
程序设计中,可以创建一个名为"Shape"的接口,定义一个公共的"calculateArea()""calculatePerimeter()"方法,表示所有形状都应具备的基本计算面积周长的功能。然后,矩形圆形正方形这三种具体的形状类会继承自这个接口,并实现这两个方法。 ```java // Shape 接口 public interface Shape { double calculateArea(); double calculatePerimeter(); } // 矩形Rectangle 实现 Shape 接口 public class Rectangle implements Shape { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } @Override public double calculateArea() { return width * height; } @Override public double calculatePerimeter() { return 2 * (width + height); } } // 圆形Circle 实现 Shape 接口 public class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * Math.pow(radius, 2); } @Override public double calculatePerimeter() { return 2 * Math.PI * radius; } } // 正方形Square 实现 Shape 接口 public class Square extends Rectangle { public Square(double sideLength) { super(sideLength, sideLength); } } ``` 在主程序中,你可以通过 Shape 类型的引用来处理这些形状,无需关心它们的具体实现: ```java List<Shape> shapes = Arrays.asList(new Rectangle(5, 10), new Circle(7), new Square(4)); for (Shape shape : shapes) { System.out.println("Shape Area: " + shape.calculateArea()); System.out.println("Shape Perimeter: " + shape.calculatePerimeter()); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值