请应用泛型编写程序。首先定义一个接口,它至少包含一个可以计算面积的成员方法。然后,编写实现该接口的连个类:正方形类和圆类。接着写一个具有泛型特点的类,要求利用这个类可以在控制台窗口输出某种图形的面积,而且这个类的类型变量所对应的实际类型可以说前面编写的正方形类或圆类。最后利用这个具有泛型特点的类在控制台窗口中分别输出给的边长的正方形的面积和给定半径的圆的面积。
L_Shape.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package l_area;
/**
*
* @author Administrator
*/
public interface L_Shape {
public abstract double mb_getArea();//计算并返回形状的面积
}//接口L_Shape结束
L_Interface.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package l_area;
/**
*
* @author Administrator
*/
public class L_Interface <T extends L_Shape>{
public double sq_getArea(T t)
{
return t.mb_getArea();
}
}//类L_Interface结束
L_Circle.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package l_area;
/**
*
* @author Administrator
*/
public class L_Circle implements L_Shape{
public double m_radius;//半径
public L_Circle(double r)
{
m_radius=r;
}//J_Circle构造方法结束
//计算并返回形状的面积
public double mb_getArea()
{
return (Math.PI*m_radius*m_radius);
}
}//类J_rectangle结束
L_Square.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package l_area;
/**
*
* @author Administrator
*/
public class L_Square implements L_Shape{
public double length;
public L_Square(double l)
{
length=l;
}//J_Rectangle构造方法结束
//计算并返回形状的面积
public double mb_getArea()
{
return (length*length);
}//方法mb_getArea结束
}//接口L_Shape结束
L_Area.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package l_area;
/**
*
* @author Administrator
*/
public class L_Area {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
L_Interface<L_Circle> a=new L_Interface<L_Circle>();
System.out.print("半径为5的圆的面积是");
System.out.println(a.sq_getArea(new L_Circle(5)));
L_Interface<L_Square> b=new L_Interface<L_Square>();
System.out.print("半径为5的正方形的面积是");
System.out.println(b.sq_getArea(new L_Square(5)));
}//main结束
}//类L_Area结束