创建interfacedemo包,包中定义: (1)Shape接口,在该接口中包含计算形状面积computeArea()和计算形状周长computePerimeter()的抽象方法; (2)定义Circle类实现Shape接口,并重写toString()方法,toString()方法中返回圆的基本信息(包括半径、面积与周长); (3)定义Rectangle类实现Shape接口,并重写toString()方法,toString()方法中返回矩形的基本信息(包括长、宽、面积与周长); (4)定义InterfaceTest类,创建圆与矩形的对象,并直接打印输出圆和矩形的对象。
时间: 2024-01-07 11:02:56 浏览: 77
Java基于Scanner对象的简单输入计算功能示例
好的,以下是代码实现:
Shape.java:
```java
package interfacedemo;
public interface Shape {
// 计算形状面积
double computeArea();
// 计算形状周长
double computePerimeter();
}
```
Circle.java:
```java
package interfacedemo;
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double computeArea() {
return Math.PI * radius * radius;
}
@Override
public double computePerimeter() {
return 2 * Math.PI * radius;
}
@Override
public String toString() {
return "Circle[radius=" + radius + ", area=" + computeArea() + ", perimeter=" + computePerimeter() + "]";
}
}
```
Rectangle.java:
```java
package interfacedemo;
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double computeArea() {
return length * width;
}
@Override
public double computePerimeter() {
return 2 * (length + width);
}
@Override
public String toString() {
return "Rectangle[length=" + length + ", width=" + width + ", area=" + computeArea() + ", perimeter="
+ computePerimeter() + "]";
}
}
```
InterfaceTest.java:
```java
package interfacedemo;
public class InterfaceTest {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(3, 4);
System.out.println(circle);
System.out.println(rectangle);
}
}
```
在运行程序之前,请确保以上代码文件都在一个名为`interfacedemo`的包中。该程序创建了一个圆的对象和一个矩形的对象,并直接打印输出它们的信息。运行程序后,会看到圆和矩形的基本信息,包括它们的面积和周长。
阅读全文