定义接口Shape,其中包括一个方法size(),设计“矩形”、“圆”、“圆柱体”等类实现Shape接口,其size()方法分别表示计算矩形面积、圆面积、圆柱体的体积。分别创建代表“矩形”、“圆”、“圆柱体”的三个对象存入一个Shape类型的数组中,通过调用size()方法将数组中各类图形的大小输出。
源代码如下:
package pk1;
interface Shape{//接口
double size();
}
class Rectangle implements Shape{//矩形类
double width;
double height;
public Rectangle(double i,double j) {
width=i;height=j;
}
public double size() {
return width*height;//返回矩形面积
}
}
class Circle implements Shape{//圆类
double r;
public Circle(double r) {
this.r=r;
}
public double size() {
return Math.PI*r*r;//返回圆面积
}
}
class Cylinder implements Shape{//圆柱体类
double r;
double h;
public Cylinder(double r,double h) {
this.r=r;
this.h=h;
}
public double size(){
return Math.PI*r*r*h;//返回圆柱体体积
}
}
public class inform {
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape s[]=new Shape[3];
s[0]=new Rectangle(4.9,5.6);
s[1]=new Circle(3.2);
s[2]=new Cylinder(6.89,9.23);
for(int k=0;k<s.length;k++)
System.out.println(s[k].size());
}
}