2016-11-09 112 views
0

我收到了一份旨在測試計算器有效性的作業。他們給了我們一個默認的課程去看起來像這樣:如何調用和測試具有相同名稱的方法?

public class Calculator { 
     Double x; 
     /* 
     * Chops up input on ' ' then decides whether to add or multiply. 
     * If the string does not contain a valid format returns null. 
     */ 
     public Double x(String x){ 
       return new Double(0); 
     } 

     /* 
     * Adds the parameter x to the instance variable x and returns the answer as a Double. 
     */ 
     public Double x(Double x){ 
       System.out.println("== Adding =="); 
       return new Double(0); 
     } 

     /* 
     * Multiplies the parameter x by instance variable x and return the value as a Double. 
     */ 
     public Double x(double x){ 
       System.out.println("== Multiplying =="); 
       return new Double(0); 
     } 

} 

你想擴大這個類,旨在成爲一個測試設備。以下說明如下:

  1. 創建一個名爲testParser()的方法。
  2. 測試,X( 「12 + 5」)返回一個雙用值17
  3. 測試,X( 「12×5」)返回一個雙用值60
  4. 測試,X(」 12 [3「)返回null,因爲[不是有效的運算符。

下面是我所做的電流變化:

public class TestCalculator { 
     Double x; 
     /* 
     * Chops up input on ' ' then decides whether to add or multiply. 
     * If the string does not contain a valid format returns null. 
     */ 
     public Double x(String x){ 
       return new Double(0); 
     } 
     public void testParsing() { 



     } 
     /* 
     * Adds the parameter x to the instance variable x and returns the answer as a Double. 
     */ 
     public Double x(Double x){ 
       System.out.println("== Adding =="); 
       x("12 + 5"); 
       return new Double(0); 
     } 
     /* 
     * Multiplies the parameter x by instance variable x and return the value as a Double. 
     */ 
     public Double x(double x){ 
       System.out.println("== Multiplying =="); 
       x("12 x 5"); 
       return new Double(0); 
     } 
} 

什麼,我主要是困惑的是我是如何調用實際的方法,因爲他們沒有得到任何唯一的名稱叫並且您不能更改方法的名稱,因爲這會更改數據類型。此外,他們爲什麼使用字符串數據類型來添加和相乘數字?如何開始編寫testParsers()方法會有幫助。謝謝。

+3

過去了那麼你可以有效地指定由寂寂重載使用哪種方法的參數正確的方法。如果你傳入的參數是'String',它將使用接受一個字符串的重載等。至於「爲什麼他們使用String數據類型來添加和乘數?」 - 當然,這是一個問題,你應該問誰分配問題,而不是我們。 –

+0

看來你是在java和本網站上都開始了,你應該看看像你這樣的其他問題,這裏是一個可能會讓你感興趣的問題: http://stackoverflow.com/questions/21058166/is可能的多個方法與同名但不同的參數在一個 –

回答

0
Calculator c = new Calculator(); 
String p1 = "a"; 
Double p2 = 1; 
double p3 = 2; 

c.x(p1); 
c.x(p2); 
c.x(p3); 

所有3個調用都會調用不同的方法。

1

你正在處理的是方法重載。您有3個名稱相同的方法,但它們具有不同的方法簽名。要調用特定的方法,只需傳入適當的參數即可。在這種情況下,你做的事:

Calculator c = new Calculator(); 
String string = "b"; 
Double doubleObject = 1; 
double doublePrimitive = 2; 

c.x(string); 
c.x(doubleObject); 
c.x(doublePrimitive); 

Java將調用基於被在

+0

這不是多少多態(作爲許多類型之一),但更好地描述爲操作重載。 – Obicere

+0

@Obicere我做了改變。謝謝。 – BlackHatSamurai

+0

因此,如果例如我調用「c.x(doubleObject)」,這將返回添加方法? – Taylor

相關問題