I am trying to understand the difference between 2 methods that have the same name. This is the code I am trying to understand…
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));
}
Could someone please explain the difference between the 2 distance() methods. What does the type MyPoint actually mean? Why does 1 of the methods have a single MyPoint object, whereas the other method has 2 MyPoint objects?
MyPointis the type of the object. In thedistance(MyPoint p1, MyPoint p2)method, for example, it means that you are passing in 2 objects to this method – the first object is aMyPointobject called p1, and the second object is anotherMyPointobject called p2.The difference between the 2 println statements is that the first one runs the
distance(MyPoint)method, and the second one runs thedistance(MyPoint, MyPoint)method. Additionally, the first method runs thedistance()from theMyPoint p1object to the one passed in to the method (p2), whereas the seconddistance()method is a static call which calculates the distance between the 2MyPointobjects passed in to the method (p1andp2).