Java指导书练习题——类作为类型实参的泛型应用

类作为类型实参的泛型应用

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;
    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值