2013-08-17 113 views
1

我有一個對象數組,其中一些使用包含基類中不可用函數的擴展版本。當數組由基類定義時,如何通過數組調用該函數?Java - 通過對象數組在擴展類中調用函數

Shape[] shapes = new Shape[10]; 

shapes[0] = new Circle(10) //10 == radius, only exists in circle class which extends Shape 

shapes[0].getRadius(); //Gives me a compilation error as getRadius() doesn't exist in the  
Shape class, only in the extended Circle class. Is there a way around this? 

回答

1

Shape類不包含的方法getRadius,因此沒有鑄造的對象ShapeCircle,該方法將不可見。所以,你應該這樣做:

((Circle)shapes[0]).getRadius(); 
0

如果你確定你的目標是在給定的子類,使用CAST:

((Circle)shapes[0]).getRadius(); 
0

試試這個

if (shapes[0] instanceof Circle) 
     ((Circle)shapes[0]).getRadius();