2017-02-18 60 views
-1
TwoDShape shapes[] = new TwoDShape[2]; 
shapes[0] = new Triangle("outlined",8.0,12.0); 
shapes[1] = new Rectangle(10); 

有一個超類是TwoDShape,它有子類(Triangle,Rectangle vs.)我很理解超類引用可以引用子類object.Yet,我不能瞭解上面發生了什麼。我們創建了一個對象,它是shapes?我知道,數組是對象(我不確定它是否相關)。你能解釋一下這些語句的邏輯嗎?瞭解對象陣列

+1

在其中創建TwoDShape'對象,然後存儲對象的'陣列 - 這是全部 – mic4ael

+1

'shapes [0]'指數組中的單個_entry_,它是一個'TwoDShape'對象。 –

+0

你在這裏的代碼和'TwoDShape shapes0 = new Triangle(...); TwoDShape shapes1 = new Rectangle(...);',就類型和賦值而言。 –

回答

2

數組是對象。您創建了一個數組對象。

該數組可以保存對其類型的其他對象的引用。並且,當您像這樣分配陣列的單個元素時,

shapes[0] = new Triangle("outlined",8.0,12.0); 
shapes[1] = new Rectangle(10); 

將對象分配給數組中的已分配索引。這是可能的,因爲超級類型可以容納的對象Sub類型。

這是一個brief tutorial on Arrays


希望對您有所幫助!

1

TwoDShape是一個超類,它很清楚。現在另一個Triangle和Rectangle是TwoDShape類的實現。

這就是我們能夠做到這一點的原因。

1

你有像這樣的類似這樣的一流的設計:

class TwoDShape { 
} 

class Triangle extends TwoDShape { 

    private String s; 
    private double s2; 
    private double s3; 

    public Triangle(String s, double s2, double s3) { 
     this.s = s; 
     this.s2 = s2; 
     this.s3 = s3; 
    } 
    //getters and setter 
} 

class Rectangle extends TwoDShape { 

    private int s; 

    public Rectangle(int s) { 
     this.s = s; 
    } 
    //getters and setter 
} 

public class Main { 

    public static void main(String[] args) { 
     TwoDShape shapes[] = new TwoDShape[5]; 
     shapes[0] = new Triangle("outlined", 8.0, 12.0); 
     shapes[1] = new Rectangle(10); 
    } 
} 

所以三角和矩形類從TwoDShape類,當你創建A型TwoDShape shapes[] = new TwoDShape[5];的陣列擴展爲,所以,你可以使用數組中的對象TriangleTriangle

1

在這個聲明TwoDShape shapes[] = new TwoDShape[5];你在說,請爲TwoDShape對象創建一個空的5項佔位符數組。

然後這個代碼:

shapes[0] = new Triangle("outlined",8.0,12.0); 
shapes[1] = new Rectangle(10); 

它指示該地方TwoDShape對象的一個​​實例(在此情況下,可以是TwoDShape,三角波,和矩形),以陣列。

0

您創建了一個TwoDShape類型的名爲形狀的陣列。所以它可以存儲類型的數據TwoDShapeTwoDShape陣列中的給定

然後你存儲超級類型的對象TriangleRectangle繼承從類TwoDShape