2012-04-08 88 views
0

我想了解兩個具有相同名稱的方法之間的區別。這是我試圖理解代碼...對象變量類型是什麼意思?

public class Test { 
    public static void main(String[] args) { 
     MyPoint p1 = new MyPoint(); 
     MyPoint p2 = new MyPoint(10, 30.5); 
     System.out.println(p1.distance(p2)); 
     System.out.println(MyPoint.distance(p1, p2)); 
    } 
} 

class MyPoint { 
    ..... 
} 

public double distance(MyPoint secondPoint) { 
    return distance(this, secondPoint); 
} 

public static double distance(MyPoint p1, MyPoint p2) { 
    return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); 
} 

可能有人請解釋2種distance()方法之間的差異。 MyPoint實際上是什麼意思?爲什麼1個方法有一個MyPoint對象,而另一個方法有2個MyPoint對象?

回答

2

MyPoint是對象的類型。例如,在distance(MyPoint p1, MyPoint p2)方法中,這意味着您要將2個對象傳遞給此方法 - 第一個對象是MyPoint對象,稱爲p1,第二個對象是另一個MyPoint對象,稱爲p2。

2個println語句之間的區別在於第一個運行distance(MyPoint)方法,第二個運行distance(MyPoint, MyPoint)方法。另外,第一方法運行從MyPoint p1對象到一個在傳遞到方法(p2)的distance(),而第二distance()方法是計算在通過了2個MyPoint對象的方法之間的距離(一個靜態調用p1p2)。

+0

尷尬的問,但爲什麼在參數中可以包含類名,但不是像S​​tring或int類型? – 2012-04-08 08:29:56

+0

它也可以包含。如果它的東西像一個int或一個布爾值,它指的是原始類型的數據,如簡單數字或真/假。如果它像String,MyPoint或任何其他類名一樣,則表示它是一種對象類型,它可能比簡單的原始數據類型更復雜 – wattostudios 2012-04-08 08:45:29

+0

我知道我誤解的地方。非常感謝你。 – 2012-04-08 09:04:31

0

區別在於你的計算方式。首先由實例的狀態執行,然後以「靜態」方式執行第二個狀態。

你可能想看看真正的用法。如果它像實用程序一樣,將它變爲靜態更有意義。

0

距離是用於計算給定爲輸入的兩點之間的距離的方法。

Class MyPoint描述了空間中的點。現在在這個類方法的距離(Mypoint X)爲您提供了從作爲參數傳遞的參考點這個點的距離,而靜態方法簡單的返回兩個點之間的距離,通過

0

也許你的問題是關於靜態方法?

p1.distance(p2) 

這叫MyPoint的成員函數,這個呼叫來自MyPoint P1的特定實例 然而

MyPoint.distance(p1, p2) 

調用MyPoint,它不需要任何實例的靜態方法,但你必須添加MyPoint。告訴編譯器你正在引用一個靜態方法或字段。