abstract class shape
{
  public abstract double area();
}
class circle extends shape
{
  double r;
  circle (double r)
    {
        this.r=r;
     }
  
public double area()
  {
return (3.14*r*r);
  }
}
class rectangle extends shape
{
 double a,b;
 rectangle(double a,double b)
{
 this.a=a;
 this.b=b;
}
public double area()
{
 return a*b;
}
}抽象类的使用,如何实例化并操作?

解决方案 »

  1.   

    public static void main(String[] args) {
    shape shape = new rectangle(1,2);
    System.out.println(shape.area());
    shape shape1 = new circle(2);
    System.out.println(shape1.area());
    }
      

  2.   


    当然也可以
            rectangle shape = new rectangle(1,2);
            System.out.println(shape.area());
            rectangle shape1 = new circle(2);
            System.out.println(shape1.area());不过按照面向对象的观点,还是第一种比较规范。
      

  3.   

    比如有个方法
    double calAera(shape s) {
        return s.area();
    }
    对于这个方法来说,它不需要关心这个shape实例是什么,只知道你给我一个shape,我就给你计算面积。
    这样就不需要针对每种shape做判断和处理,也就达到共通化
      

  4.   

    public class Test{
    public static void main(String []args
    {
    circle c=new circle();
    System.out.println(c.area());
    rectangle r=new rectangle();
    System.out.println(r.area());
    }
    }