java中以类为类型实参创建泛型对象

题目如下:

        分别声明一个泛型类 Cylinder <E>、一个圆形类 Circle、一个矩形类 Rect。在主类中分别以类 Circle 和 类 Rect 为类型实参创建泛型对象,然后计算各自图形的面积,并调用泛型类的方法输出各自的计算机结果,使程序运行结果如下图所示:

       

        · 首先可以判断出主类是 public class Cylinder<E>,通过结果图“求体积”可判断出Circle类和Rect类里的方法是为了得出长方体和圆柱体的底部面积。因此主类只关心底面积是多少,不关心底部的具体形状,因此用E作为底(底是变化的那个),主类里应该设有定义泛型类的构造方法,求体积的方法。而Circle类和Rect类就是除了构造方法外还要设有toString()方法以获得底部面积()

代码如下:


public class Cylinder<E> {
	E bottom;
	double height;
	
	public Cylinder(E bottom,double height) {
		this.bottom = bottom;
		this.height = height;
	}
	
	public double volumn() {
		//泛型对象只能调用从Object类继承或重写的方法
		String s = bottom.toString();
		double area = Double.parseDouble(s);
		return area * height;
	}
	
	public static void main(String[] args) {
		Rect rect = new Rect(8,5);
		//创建泛型类‘长方体’对象c1
		Cylinder <Rect> c1 = new Cylinder<>(rect,12); //菱形语法 以类为类型实参创建泛型对象
		System.out.println("长方体的体积是:" + c1.volumn());
		
		Circle circle = new Circle(5);
		//创建泛型类‘长方体’对象c1
		Cylinder <Circle> c2 = new Cylinder<>(circle,7);
		System.out.println("圆柱体的体积是:" + c2.volumn());
		
	}
}

class Circle{
	double r,area;
	public Circle(double r) {
		this.r = r;
	}
	//泛型类中的泛型变量bottom只能调用Object类中的方法,因此类Circle和类Rect中都必须
	//重写Object类中的toString()方法,从而获得底部面积
	public String toString() {
		area = 3.14 * r * r;
		return area + "";
	}
}

class Rect{
	double length,width,area;
	public Rect(double length,double width) {
		this.length = length;
		this.width = width;
	}
	
	public String toString() {
		area = width * length;
		return area + "";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值