我在学习java泛型类时遇到了这样一个问题:定义了两个基本类圆形(Circle)、长方形(Rectangle),定义一个泛型类体积(Volume),我希望通过Volume类可以实现对底面积为圆、长方形求体积,应该怎样在Volume类中获取Circle或者Rectangle的面积呢?
package ex9.generalclass;import java.text.DecimalFormat;public class GeneralClass { public static void main(String[] args) {
// TODO Auto-generated method stub
Circle c1=new Circle(3.5);
Volume<Circle> c1v=new Volume<Circle>(c1,2.5);
c1v.showVolume();
}}
class Circle{//圆形
final double PI=3.14159;
private double radius;
public Circle(double radius){
this.radius=radius;
}
public double getArea(){
return PI*radius*radius;
}
}class Rectangle{//长方形
private double length,width;
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
public double getArea(){
return length*width;
}
}class Volume<E>{//体积泛型
E area;
private double height;
public Volume(E area,double height){
this.area=area;
this.height=height;
}
public void showVolume(){
DecimalFormat DF=new DecimalFormat("#.##");
System.out.println("体积为"+
DF.format(1/3*area.getArea()*height)));//这里应该怎样获取底面积?
}
}
package ex9.generalclass;import java.text.DecimalFormat;public class GeneralClass { public static void main(String[] args) {
// TODO Auto-generated method stub
Circle c1=new Circle(3.5);
Volume<Circle> c1v=new Volume<Circle>(c1,2.5);
c1v.showVolume();
}}
class Circle{//圆形
final double PI=3.14159;
private double radius;
public Circle(double radius){
this.radius=radius;
}
public double getArea(){
return PI*radius*radius;
}
}class Rectangle{//长方形
private double length,width;
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
public double getArea(){
return length*width;
}
}class Volume<E>{//体积泛型
E area;
private double height;
public Volume(E area,double height){
this.area=area;
this.height=height;
}
public void showVolume(){
DecimalFormat DF=new DecimalFormat("#.##");
System.out.println("体积为"+
DF.format(1/3*area.getArea()*height)));//这里应该怎样获取底面积?
}
}
public class GeneralClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
Circle c1=new Circle(3.5);
Volume<Circle> c1v=new Volume<Circle>(c1,2.5);
c1v.showVolume();
}
}abstract class HasArea{
public abstract double getArea();
}class Circle extends HasArea{//圆形
final double PI=3.14159;
private double radius;
public Circle(double radius){
this.radius=radius;
}
@Override
public double getArea(){
return PI*radius*radius;
}
}
class Rectangle extends HasArea{//长方形
private double length,width;
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
@Override
public double getArea(){
return length*width;
}
}
class Volume<E extends HasArea>{//体积泛型
E area;
private double height;
public Volume(E area,double height){
this.area=area;
this.height=height;
}
public void showVolume(){
DecimalFormat DF=new DecimalFormat("#.##");
System.out.println("体积为"+
DF.format(area.getArea()*height));//这里应该怎样获取底面积?
}
}
简单改了一下,看看是不是你需要的