jump to navigation

Operator overloading in Java using Jython August 24, 2006

Posted by pauloh81 in Uncategorized.
trackback

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)

About these ads

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: