302班

java突击队
posts - 151, comments - 74, trackbacks - 0, articles - 14
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

类的继承实例—Triangle

Posted on 2007-04-07 22:12 停留的风 阅读(619) 评论(0)  编辑  收藏 所属分类: Java程序集合

abstract class GeometricObject {
  private String color = "white";
  private boolean filled;
 
  protected GeometricObject()
  {}
 
  /** 颜色和填充 */
  protected GeometricObject(String color, boolean filled)
  {
    this.color = color;
    this.filled = filled;
  }
 
  /**颜色get方法 */
  public String getColor()
  {
    return color;
  }
 
  /** 颜色的set方法*/
  public void setColor(String color)
  {
    this.color = color;
  }
 
  /** 填充的定义 */
  public boolean isFilled()
  {
    return filled;
  }
 
  /** 建立fill的set方法 */
  public void setFilled(boolean filled)
  {
    this.filled = filled;
  }
  public abstract double getArea();
  public abstract double getPerimeter();
}


public class Triangle extends GeometricObject
{
  private double side1=1.0;
  private double side2=1.0;
  private double side3=1.0;
  //无参构造器
  public Triangle()
  {
   this(1.0,1.0,1.0,"red",false);
  }
  public Triangle(double side1,double side2,double side3)
  {      
    this(side1,side2,side3,"red",false);  
  }
  //有参构造器
   public Triangle(double side1, double side2,double side3,String color,boolean filled)
  {
    super(color,filled);
    this.side1=side1;
    this.side2=side2;
    this.side3=side3;   
  }
  //定义Side1的Get和Set方法
  public double getSide1()
  {
   return side1;
  }
  public void setSide1(double side1)
  {
    this.side1=side1;
  }
  //定义Side2的Get和Set方法
   public double getSide2()
  {
   return side2;
  }
  public void setSide2(double side2)
  {
    this.side2=side2;
  }
  //定义Side3的Get和Set方法
  public double getSide3()
  {
   return side3;
  }
  public void setSide3(double side3)
  {
    this.side3=side3;
  }
  //求面积
  public double getArea()
  {
    double p;
    p=(side1+side2+side3)/2;
    double s;
    s=Math.sqrt(p*(p-side1)*(p-side2)*(p-side3));
    return s;
  }
  //计算周长
  public double getPerimeter()
  {
    return (side1+side2+side3);
  }
  //定义toString文本说明
  public String toString()
  {
    return "Triangle: side1 = " + side1 + " side2 = " + side2 +" side3 = " + side3; 
  }
   public static void main(String[] args)
  {
      Triangle tr = new Triangle(3.6,5.8,3.5);
      System.out.println("The perimeter of Triangle is :"+tr.getPerimeter());
      System.out.println("The area of Triangle is :"+tr.getArea());
      System.out.println("The color of Triangle is :"+tr.getColor());
      System.out.println("The filled of Triangle is :"+tr.isFilled());
  }

}


只有注册用户登录后才能发表评论。


网站导航: