A constructor is a method with the class's name and no return type that runs on new: Point(int x, int y) { this.x = x; this.y = y; }. this is the object being worked on; this.x is the field and plain x the parameter when they share a name, which is the convention. A class with no constructor gets an empty one for free; as soon as you write one, new Point() without arguments stops compiling unless you also write that.
Methods can take other objects of the same class as parameters and read their fields: double distanceTo(Point other) { ... other.x ... }. static methods on a class are often factories, alternative ways to make an instance: static Point origin() { return new Point(0, 0); }.
class Temperature {
double celsius;
Temperature(double celsius) {
this.celsius = celsius;
}
double fahrenheit() {
return celsius * 9 / 5 + 32;
}
}Your task
Write class Point with int x and int y, a constructor Point(int x, int y), a method double distanceTo(Point other) (use Math.sqrt), a method Point moved(int dx, int dy) returning a new point shifted by that much, and a static method Point origin() returning (0, 0).
Hint 1
Point(int x, int y) { this.x = x; this.y = y; }
Hint 2
double distanceTo(Point other) { int dx = x - other.x; int dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } moved returns new Point(x + dx, y + dy).
Show the solution
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p.distanceTo(Point.origin()));
}
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
double distanceTo(Point other) {
int dx = x - other.x;
int dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
Point moved(int dx, int dy) {
return new Point(x + dx, y + dy);
}
static Point origin() {
return new Point(0, 0);
}
}