2016-04-22 45 views
-1

我呼籲形狀的界面,我有這樣的方法,我需要實現返回一個接口的Java

public static Shape createShape(String shapeString, int panelWidth, int panelHeight) { 
     Shapes shape = Shapes.valueOf(shapeString); 
     Shape shapey = Shape(shape); 
     Random random = new Random(); 
     int a = random.nextInt(panelWidth); 
     int b = random.nextInt((panelHeight*panelWidth)/(4*a)); 
    } 

我知道我需要返回的形狀,但是我不知道我應該如何這樣做

+0

要返回一個對象只需輸入:return shapey; –

回答

0

你是什麼意思「我需要返回一個形狀」?請更清楚。

你不能實例化一個接口,您需要實例化一個實現接口的類,例如:

class Square implements Shape { ... } 

public static Shape createShape(String shapeString, int panelWidth, int panelHeight) { 
    ... 
    return new Square(); 
} 
+0

你可以使用匿名類而不是你做的。 http://stackoverflow.com/questions/9157784/java-interface-with-new-keyword-how-is-that-possible – Gendarme

+0

我很確定,這不是什麼OP是想要做的。 –

0

如果你沒有叫Shape的方法那麼這個聲明是無效的

Shape shapey = Shape(shape); 

而不會編譯...另一方面... ...返回一個接口不像返回一個類一樣,因爲您需要添加return語句和接口,或者一些物體實現接口...

public static Shape createShape(String shapeString, int panelWidth, int panelHeight) { 
     Shapes shape = Shapes.valueOf(shapeString); 
     Shape shapey = Shape(shape); 
     Random random = new Random(); 
     int a = random.nextInt(panelWidth); 
     int b = random.nextInt((panelHeight*panelWidth)/(4*a)); 
     return shapey;//this will do the trick 
    }