A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

先说明,我代码有问题,不是偷懒。
这个是我有错误的代码,我不理解的就是怎么把Square和Circle的getArea用进去啊。

interface Shape{
public double getArea();
}
class Square implements Shape{
double sideLen;
Square(double sideLen){
  this.sideLen=sideLen;
}
public double getArea(){
  return sideLen*sideLen;
}
}
class Circle implements Shape{
int radius;
  public double getArea(){
  return Math.PI*radius*radius;
  }
}
public class TestGeneric<Shape>{
Shape shape;
TestGeneric(Shape shape){
  this.shape=shape;
}
public double calcArea(){
  return shape.getArea();
}
public static void main(String[]args){
  Square sq=new Square(3.3);
  TestGeneric<Square> a=new TestGeneric<Square>(sq);
  a.calcArea();
  
}

}

评分

参与人数 1技术分 +1 收起 理由
黑马张扬 + 1

查看全部评分

3 个回复

倒序浏览
class TestGeneric{
       
        public double calcArea(Shape shape){//这里传入接口变量
                return shape.getArea();//调用面积函数
        }
        public static void main(String[]args){
                Square sq=new Square(3.3);
                TestGeneric a=new TestGeneric();
                System.out.println(a.calcArea(sq));//return 的是double值,用打印语句才能看到效果
          
        }

}
回复 使用道具 举报
不要把shape放在构造函数里初始化,那样你再求圆的面积又要new一个TestGeneric对象
回复 使用道具 举报
陆强强 发表于 2012-7-13 17:52
不要把shape放在构造函数里初始化,那样你再求圆的面积又要new一个TestGeneric对象
...

嗯 试过了 您说的果然方便
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马