首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

沿袭小例子

2012-12-19 
继承小例子public class Shape{private String nameprotected double areapublic Shape(String name){th

继承小例子

public class Shape{   private String name;   protected double area;   public Shape(String name){       this.name=name;          }   public String getName(){     return this.name;   }   public double countArea(){        return 0.0;   } }class Rectangle extends Shape{     private double length,width;          public Rectangle(String name,double length,double width){       super(name);       this.length=length;       this.width=width;       }     public double countArea(){        return this.area=length*width;              }      }class Triangle extends Shape{     private double length,width;          public Triangle(String name,double length,double width){       super(name);       this.length=length;       this.width=width;       }     public double countArea(){        return this.area=1/2*length*width;              }      }class Circle extends Shape{    private double r;    public Circle (String name,double r){       super(name);       this.r= r;    }    public double countArea(){     return this.area=Math.PI*Math.pow(r,2.0);            }     }class TestShape{        public static void calShapeArea(Shape r){       System.out.println(r.countArea());     }     public static void main(String[] args){      Shape r = new Rectangle("矩形",58,76);                calShapeArea(r);       r = new Circle("圆形",12);        calShapeArea(r);       r= new Triangle("三角形",378,38);        calShapeArea(r);       r= new Circle("圆形",38);        calShapeArea(r);     }}
public interface ShapeInterface{  public static final double PI=3.1415926;  public static void countArea();  public static double getArea();  }   interface comparableShape extends ShapeInterface{}class CircleImpl implements ShapeInterface{     private double r;     private double area;     public CircleImpl(double r){         this.r=r;     }     public void countArea(){      this.area = this.PI * Math.pow(r,2.0);       }     public double getArea(){return area;}}class Triangle implements ShapeInterface{     private double length;     private double width;     private double area;     public void countArea(){        this.area= 1/2*length*width;     }     public double getArea(){return area;}}class ShapeInterfaceApp{     public static void printShapeArea(ShapeInterface shape){         shape.countArea();     System.out.println(shape.getArea());   } public static void main(String[] args){         ShapeInterface circle = new CircleImpl(23.4);         printShapeArea(circle);}}

热点排行