应用泛型编写程序。首先定义一个接口,他至少包含一个可以计算面积的成员方法,然后编写实现该接口的两个类:正方形类和圆类。接着编写一个具有泛型特点的类,要求利用这个类可以在控制台中输出计算圆锥和方锥的体积。
下面展示一些 内联代码片
。
//先定义一个接口
interface Shape{
public double getArea();
}
//再写两个接口子类,用于两种类型体积计算
class SquareCone implements Shape{
double sL;
double H;
SquareCone(double sL,double H){
this.sL=sL;
this.H=H;
}
@Override
public double getArea(){
return (H*sL*sL)/3;
}
}
class Cone implements Shape{
double radius;
double H;
Cone(double radius,double H){
this.radius=radius;
this.H=H;
}
@Override
public double getArea(){
return (H*Math.PI*radius*radius)/3;
}
}
//
public class test<Test extends Shape>{
Test shape;
test(T shape){
this.shape=shape;
}
public double calcArea(){
return shape.getArea();
}
public static void main(String[] args){
Shape sq=new Cone(3,3);
test<SquareCone> a=new test(sq);
a.calcArea();
System.out.println("圆锥体积:"+a.calcArea());
Shape s=new SquareCone(3,3);
test<SquareCone> b=new test(s);
b.calcArea();
System.out.println("方锥体积:"+b.calcArea());
}
}