(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。 定义一个测试类ShapeTester2,在main方法中创建一个大小为10,数据类型为Shape2D的数组shape2ds。随机产生10个circle或rectangle类型的变量,向上塑形后放入数组shape2ds中。遍历shape2ds中的每一个元素,并调用draw函数。
时间: 2024-02-13 22:05:06 浏览: 43
getcolor_getcolor_Vc_鼠标钩子_
好的,以下是符合您要求的代码:
```
// Shape接口
interface Shape {
String getColor();
void setColor(String c);
}
// Shape2D接口
interface Shape2D extends Shape {
double area();
void draw();
}
// Circle类
class Circle implements Shape2D {
private String color;
private double radius;
public Circle(String c, double r) {
color = c;
radius = r;
}
@Override
public String getColor() {
return color;
}
@Override
public void setColor(String c) {
color = c;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public void draw() {
System.out.println("I am a circle.");
}
}
// Rectangle类
class Rectangle implements Shape2D {
private String color;
private double width;
private double height;
public Rectangle(String c, double w, double h) {
color = c;
width = w;
height = h;
}
@Override
public String getColor() {
return color;
}
@Override
public void setColor(String c) {
color = c;
}
@Override
public double area() {
return width * height;
}
@Override
public void draw() {
System.out.println("I am a rectangle.");
}
}
// ShapeTester类
class ShapeTester {
public static void main(String[] args) {
Circle c = new Circle("red", 2.0);
Shape sc = (Shape) c;
Shape2D s2c = c;
sc.setColor("blue");
System.out.println("Circle area: " + s2c.area());
Rectangle r = new Rectangle("green", 3.0, 4.0);
Shape sr = (Shape) r;
Shape2D s2r = r;
sr.setColor("yellow");
System.out.println("Rectangle area: " + s2r.area());
}
}
// ShapeTester2类
import java.util.Random;
class ShapeTester2 {
public static void main(String[] args) {
Shape2D[] shape2ds = new Shape2D[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) {
if (rand.nextBoolean()) {
shape2ds[i] = new Circle("red", rand.nextDouble() * 10);
} else {
shape2ds[i] = new Rectangle("green", rand.nextDouble() * 10, rand.nextDouble() * 10);
}
}
for (Shape2D shape2d : shape2ds) {
shape2d.draw();
}
}
}
```
希望这份代码能够满足您的需求!
阅读全文