Wednesday, August 16, 2006

Operator overloading in Java/Jython

Yesterday, I discovered that it is possible to add operator overloading to Java through Jython.

I created a small Point.java class:
import java.lang.String;
public class Point {
private double x, y;

public Point(double x, double y){
this.x = x; this.y = y;
}

public Point(Point other){
this.x = other.x; this.y = other.y;
}

public Point __add__(Point b) {
return new Point(this.x + b.x, this.y + b.y);
}

public String toString(){
String str = "(" + this.x + "," + this.y + ")";
return str;
}

public String __repr__(){
String str = "Point: (" + this.x + "," + this.y + ")";
return str;
}
}
I compiled this class with: javac Point.java. In the same folder I created a testPoint.py file with:
import Point

a = Point(1.0,1.0)
b = Point(2.0,2.5)
print "a = ", a
print "b = ", b
c = a + b
print "a + b = ", c
Running: jython testPoint.py, produces
a = (1.0,1.0)
b = (2.0,2.5)
a + b = (3.0,3.5)

No comments: