2013-03-12 91 views
0

我想從Box中擴展一個Cube。我的程序首先有三個部分,我做一個矩形類然後我用它來擴展一個Box類然後我擴展一個Cube。我被困在Cube部分。這是我的指示說:我該怎麼辦「Box entends Cube」

評估說明 a。立方體是長度,寬度和高度均具有相同值的框。 b。您不必添加任何其他實例變量或方法,但您必須設置Cube的構造函數以確保長度,寬度和高度都具有相同的值。

矩形:

public class Rectangle 
    { 
     // instance variables 
     private int length; 
     private int width; 

     /** 
     * Constructor for objects of class rectangle 
     */ 
     public Rectangle(int l, int w) 
     { 
      // initialise instance variables 
      length = l; 
      width = w; 
     } 

     // return the height 
     public int getLength() 
     { 
      return length; 
     } 
     public int getWidth() 
     { 
      return width; 
     } 

    } 

盒:

public class Box extends Rectangle 
{ 
    // instance variables 
    private int height; 

    /** 
    * Constructor for objects of class box 
    */ 
    public Box(int l, int w, int h) 
    { 
     // call superclass 
     super(l, w); 
     // initialise instance variables 
     height = h; 
    } 

    // return the height 
    public int getHeight() 
    { 
     return height; 
    } 

} 

和主要一個魔方:

class Cube extends Box{ 
    // instance variables 
    private int height; 
     private int length; 
    private int width; 

    public Cube(int h,int w,int l){ 
     super(h,w,l); 

    } 

    public double getheight(){ 
     return height; 

       } 
     public double getlength() { 
      return length; 
     } 

     public double getwidth() { 
      return width; 
     } 
} 

我需要知道,如果我做了一個魔方正確與否。如果我沒有做對,請幫我修復它。

+4

您複製了框中的所有內容。無論如何,什麼是立方體?它與盒子有什麼不同? – 2013-03-12 21:14:56

+0

我將按照我的指示說的去編輯我的代碼。 – user2059140 2013-03-12 21:18:11

+0

所以,指令說:「你不必添加任何額外的實例變量或方法。」但你做到了。爲什麼? – 2013-03-12 21:25:18

回答

5

立方體是平等主體各方的盒子。因此,將相同長度的參數傳遞給盒子的所有3個維度。

public class Cube extends Box{ 
    public Cube(int length) 
    { 
     super(length, length, length); 
    } 
} 
0

public class Box extends Cube {

+0

我很欣賞你的幽默感 – Kevin 2013-03-12 21:27:09

0

rgettman已經有了正確的解決方案,而只是它闡述:從立方體盒子延伸,所以可以繼承所有的(非私有)的方法和所有成員。從技術上講,它擁有所有成員,但「私人」成員不會被孩子看到或修改。除非要更改其實施的行爲,否則不需要重新聲明子類中的方法。

如果要擴展一個類,通常會使用「受保護」類型,因爲子類將能夠繼承與它有關的變量。這取決於子類是否需要直接修改成員變量。