I’ve been having a few issues trying to convert the Point program on the Dart website into Java. The Dart program is displayed below:
class Point {
num x, y;
Point(num this.x, num this.y);
Point scale(num factor) => new Point(x*factor, y*factor);
num distance() => Math.sqrt(x*x + y*y);
}
void main() {
Point a = new Point(2,3).scale(10);
print(a.distance());
}
Here’s what I’ve come up with so far:
public class PointJava {
int x, y;
public PointJava(int x, int y){
int a = x;
int b = y;
}
public PointJava scale(int factor){
PointJava j = new PointJava(factor*x, factor*y);
return j;
}
public double distance(){
double result = Math.sqrt(x*x+y*y);
return result;
}
public static void main(String[] args) {
PointJava a = new PointJava(2, 3).scale(10);
System.out.println(a.distance());
}
}
It outputs the double type number 0.0, but the Point program in Dart outputs 36.05551275463989.
The main issue is trying to convert these statements to Java:
Point scale(num factor) => new Point(x*factor, y*factor);
num distance() => Math.sqrt(x*x + y*y);
I’ve seen this type of syntax in C++, at least what little I’ve actually studied of it (I stopped when I was introduced to pointers and references). However, I asked someone else, and they told me these statements were actually used to define functions. I’m here to see if this person’s correct and how to understand what these statements mean in terms of Java.
Any aid will help. Thanks.
Your constructor should look like this:
Also, you should be using
floatordoubleinstead ofint.The
thiskeyword refers to the current object.this.xis a class variable namedxbelonging to the objectthis. It’s not really a global. Since you are accepting a parameter namedx, however, you must differentiate between the two using thethiskeyword. If you change what you call the passed parameter, you can avoid using the keyword (although there is no rational reason for doing so):