(1)定义一个接口Shape,包含两个方法:String getColor()和void setColor(String c)。 (2)定义一个扩展自Shape的接口Shape2D,包含两个新方法double area()和void draw()。 (3)定义一个类Circle实现Shape2D接口。其中area计算面积,draw打印字符串表示自己是circle。 (4)定义一个类Rectangle实现Shape2D接口。其中area计算面积,draw打印字符串表示自己是rectangle。 (5)定义一个测试类ShapeTester,在main方法中创建一个Circle类型的对象,向上塑形成Shape和Shape2D类型的引用变量sc和s2c,并调用sc.setcolor和s2c.area。同样,在main方法中创建一个Rectangle类型的对象,向上塑性成Shape和Shape2D类型的引用变量sr和s2r,并调用sr.setcolor和s2r.area。 (6)定义一个测试类ShapeTester2,在main方法中创建一个大小为10,数据类型为Shape2D的数组shape2ds。随机产生10个circle或rectangle类型的变量,向上塑形后放入数组shape2ds中。遍历shape2ds中的每一个元素,并调用draw函数。 请写出程序和执行结果。
时间: 2024-02-13 18:06:07 浏览: 10
DeclareStyleable:一个示例项目,展示如何以编程方式声明 styleable 并使用它来自定义自定义视图
以下是程序代码:
Shape.java
```java
public interface Shape {
String getColor();
void setColor(String c);
}
```
Shape2D.java
```java
public interface Shape2D extends Shape {
double area();
void draw();
}
```
Circle.java
```java
public class Circle implements Shape2D {
private String color;
@Override
public String getColor() {
return color;
}
@Override
public void setColor(String c) {
color = c;
}
@Override
public double area() {
return Math.PI * 2 * 2;
}
@Override
public void draw() {
System.out.println("I am a circle.");
}
}
```
Rectangle.java
```java
public class Rectangle implements Shape2D {
private String color;
@Override
public String getColor() {
return color;
}
@Override
public void setColor(String c) {
color = c;
}
@Override
public double area() {
return 2 * 3;
}
@Override
public void draw() {
System.out.println("I am a rectangle.");
}
}
```
ShapeTester.java
```java
public class ShapeTester {
public static void main(String[] args) {
Shape sc = new Circle();
Shape2D s2c = new Circle();
sc.setColor("red");
System.out.println("Circle area: " + s2c.area());
Shape sr = new Rectangle();
Shape2D s2r = new Rectangle();
sr.setColor("blue");
System.out.println("Rectangle area: " + s2r.area());
}
}
```
ShapeTester2.java
```java
import java.util.Random;
public class ShapeTester2 {
public static void main(String[] args) {
Shape2D[] shape2ds = new Shape2D[10];
Random random = new Random();
for (int i = 0; i < shape2ds.length; i++) {
if (random.nextBoolean()) {
shape2ds[i] = new Circle();
} else {
shape2ds[i] = new Rectangle();
}
}
for (Shape2D shape2d : shape2ds) {
shape2d.draw();
}
}
}
```
执行结果:
```
Circle area: 12.566370614359172
Rectangle area: 6.0
I am a rectangle.
I am a rectangle.
I am a circle.
I am a rectangle.
I am a circle.
I am a rectangle.
I am a rectangle.
I am a circle.
I am a circle.
I am a rectangle.
```
阅读全文