类作为类型实参的泛型应用
1.实验目的
(1)学习泛型类对象如何调用Objecr 类的方法
(2)以类为类型实参创建泛型对象。
2.实验要求
分别声明一个泛型类Cylinder一个圆形类Circle和一个矩形类Rectangle。在主类中分别以类Circle 和类 Rectangle 为类型实参创建泛型对象,然后计算各自图形的面积,并调用泛型类的方法输出各自的计算结果,使程序运行结果如图所示。
3.代码
public class Cylinder<E>{
E bottom;
double height;
public Cylinder(E bottom,double height){
this.bottom=bottom;
this.height=height;
}
public double volume(){
String s = bottom.toString();
double area=Double.parseDouble(s);
return area*height;
}
public static void main(String[] args)
{
Rectangle rect = new Rectangle(8,5);
Cylinder <Rectangle> c1=new Cylinder<Rectangle>(rect,12);
System.out.println("显示长方体的体积"+c1.volume());
Circle circle =new Circle(5);
Cylinder <Circle> c2=new Cylinder<Circle>(circle,7);
System.out.println("显示圆柱体的体积"+c2.volume());
}
}
class Circle
{
double radius,area;
public Circle(double radius)
{
this.radius=radius;
}
public String toString()
{
area = 3.14 * radius *radius;
return ""+area;
}
}
class Rectangle
{
double length, width,area;
public Rectangle(double length,double width)
{
this.length=length;
this.width=width;
}
public String toString()
{
area=length * width;
return ""+area;
}
}