Operator overloading is one of the great features of Object Oriented Languages
that Java developers can't use. Operator
overloading increases code legibility, for example
if you want to sum two Complex numbers, you have to write Complex
result = c1.sum(c2) (where c1 and c2 are two istances
of Complex class); How about Complex
result = c1 + c2. And what do you prefer between
c1 + c2 * c3 and c1.sum(c2.mul(c3)).
For this reason I'm introducing JOP. JOP is a simple compiler that allows
operator redefinition in Java.
JOP is based on a subset of Java language syntax called Featherweight
Java (FJ); It is a small pre-processor that translates FJ
+ Operator redefinition syntax (jopc
syntax) into Java files the java compiler (javac) can process
and transform into bytecode.
Let's define a Complex class using the FJ syntax:
class Complex extends Object {
int _real, _ima;
Complex(int real, int ima) {
super();
this._real = real;
this._ima = ima;
}
int getReal() { return _real; }
int getIma() { return _ima; }
}
Now we add the operator plus (+) and times (*) redefinition for the class Complex:
// Adds the Complex number
static Complex operator +(Complex a, Complex b) {
return new Complex(a.getReal() + b.getReal(), a.getIma() + b.getIma());
}
// Adds an integer wth a Complex
static Complex operator +(int a, Complex b) {
return new Complex(a + b.getReal(), b.getIma());
}
static Complex operator +(Complex a, int b){
return new Complex(a.getReal() + b, a.getIma());
}
// Multiply two complex number
static Complex operator *(Complex a, Complex b){
return new Complex(a.getReal() * b.getReal() - a.getIma() * b.getIma(),
a.getReal() * b.getIma() + a.getIma() * b.getReal());
}
Here there is the complete listing Complex class.
Now we can define a test case (TestCase.jop) used for testing the Complex class:
class TestCase extends Object{
TestCase(){ super(); }
Complex sum(Complex a, Complex b) { return a + b; }
Complex mul(Complex a, Complex b){ return a * b; }
Complex sum(Complex a, int b) { return a + b; }
}
Now compile the two classes with the jop compiler:
jopc Complex.jop TestCase.jop
And the file Complex.java and TestCase.java will be produced.
Now you can create a simple Java class in order to execute the test cases:
class Main{
private static String toString(Complex c) {
return c.getReal() + "+" + c.getIma() + "i";
}
public static void main(String[] args){
TestCase t = new TestCase();
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(2, 2);
Complex result = t.sum(c1, c2);
System.out.println("(" + toString(c1) + ") + (" + toString(c2) + ") = (" + toString(result) + ")");
}
}
Compile with the standard Java compiler:
javac Main.java Complex.java TestCase.java
Execute it:
java Main
And the result will be:
(1 + 2i) + (2 + 2i) = (3 + 4i)