2014-04-07 95 views
0

的方法我想打電話給名爲「中心」,我用它來打印對象的中心,作爲一個字符串的具體方法。我想要這個方法接受來自這些類的任何對象。對象的中心是前兩個int值(x,y)。所有這些類都是從Circle2類繼承的,因此共享此方法。我在這個類的主要方法中調用這個方法(即center()方法)。我打算創建的方法應該輸出(替換main中的println方法)這些對象中心的值(我最終將放置在ArrayList中,我將不得不復審其過程,因爲我不能回想一下我會以什麼方式去做這件事)。任何這些任何洞察將是非常有益的。創建接收多態輸入

簡而言之 - 我的意思是在這個類中創建一個方法,它將接受任何在這個主體中構造的對象(因爲他們目前是)作爲輸入,然後輸出調用center()方法的結果,他們都有共同之處。

道歉,如果我的解釋並不完全清楚 - 如果它是不完全清楚我的意思做,我會很樂意嘗試給予進一步澄清的問題。

public class TestPoly2 
{ 
    /** 
    * Constructor for objects of class TestPoly2 
    */ 
    public TestPoly2() 
    { 

    } 

    public String showCenter() 
    { 
     return "This method is supposed to output (replacing the println methods in the main) the values for centres of these objects (which I will eventually place within an ArrayList (whose process I'll have to review, as I can't recall by what means I would go about this) "; 
    } 

    public static void main(String []args) 
    { 
     Circle2 one = new Circle2(5, 10, 4); 
     Cylinder2 two = new Cylinder2(8, 7, 4, 12); 
     Oval2 three = new Oval2(3, 4, 9, 14); 
     OvalCylinder2 four = new OvalCylinder2(11, 14, 15, 10, 12); 

     System.out.println(one.center()); 
     System.out.println(two.center()); 
     System.out.println(three.center()); 
     System.out.println(four.center()); 
    } 
} 

的方法(中心()),我一直在引用如下:

public String center() 
{ 
    return "center is at (" + x + "," + y + ")"; 
} 
+0

你想寫可以採取任何這些類作爲參數的方法,或者是你想寫每個類的實現方法是什麼? – Jason

+0

我想寫一個方法,可以採取存儲在ArrayList中的對象,並使用中心()方法內的對象,以報告主方法中最後一個黑色代碼內的輸出。基本上做這個代碼的工作'System.out.println(one.center());' – Alex

+0

在本文中,[Java的繼承](http://java8.in/unit-2-prog-6-繼承的java /),你可以參考「原因使用繼承」部分... –

回答

0

這是正確的方法噸o執行任務。

public static void showCenter(Circle2 object) 
    { 
     System.out.println(object.center()); 
    } 

對於任何好奇的人,當然。 謝謝你的幫助,夥計們。

1

U可以試試這個:

public interface Shape { 

    public String center(); 
} 

public class Circle2 implements Shape { 
    //ur rest of the code here... 

    @Override 
    public String center() { 
     // return statement here. 
    } 
} 

編輯烏爾方法是這樣的:

public String showCenter(Shape shape) { 
    return shape.center(); 
} 
+0

您在這裏提供的解決方案並不完全符合我設置的情況。我希望在這個類中創建一個方法,它將接受在這個主體中構造的任何對象,而不會在對象的類中進行任何更改。我只需要了解如何通過使用對象的ArrayList中的給定對象(它類似於main中給出的對象)來創建一個執行打印center()方法的輸出的任務的方法。 – Alex