日期:2014-05-20  浏览次数:20876 次

正方形继承长方形问题 java
这是长方形的类 正方形的构造方法怎么继承长方形的
lass Rectangle{
  private int x1;
  private int x2;
  private int y1;
  private int y2;

  public Rectangle(int x1,int x2,int y1,int y2){
  this.x1=x1;
  this.x2=x2;
  this.y1=y1;
  this.y2=y2;
  }
  public int getHeight(){
  int aHeight=0;
  aHeight=Math.abs(x1-x2);
  return aHeight;
  }
  public int getWidth(){
  int aWidth=0;
  aWidth=Math.abs(y1-y2);
  return aWidth;
  }
  public int getPerimeter(){
  int aPerimeter=0;
  aPerimeter=getHeight()*2+getWidth()*2;
  return aPerimeter;
  }
  public int getArea(){
  int aArea=0;
  aArea=getHeight()*getWidth();
  return aArea;
  }
}

------解决方案--------------------
Java code
public class Square extends Rectangle {
   private int length;
   public Square(int x, int y, // 左边顶点坐标
                 int length // 边长
) {
     super(x, y, x + length, y + length);
     this.length = length;
   }

   public int getLength() {
     return length;
   }

    //.奶.奶.的.,.说.老.子.回.复.正.文.中.有.非.法.词.或.词.组.!
    //.后.续.两.个.方.法.不.覆.盖.也.可.以.,.只.是.举.个.例.子,如.果.是.其.他.例.子,.
    //.原.来.代.码.开.销.很.大.的.话.,.建.议.覆.盖。
    //.在.你.这.个.例.子.中.,.也.建.议.在.Rectangle中.设.置.width/height.属.性.,.在.构.造.的.时.候.一.并.计.算.,.这.样.加.快.速.度

   @Override
   public int getWidth() {
     return length;
   }

   @Override
   public int getHeight() {
     return length;
   }
}