I wrote a class to represent complex numbers in Processing (which I call Complex
). I want to implement basic arithmetic functions on complex numbers. However, if I declare the return type of a method to be Complex
and try to return a new object, I get an error which says that says
"Void methods cannot return a value". I also get errors for the parentheses after the function name, as well as the comma separating the x
and y
parameters.
However, I have noticed that if I change the return type to something built-in (such as int
or String
) and return some arbitrary value of the correct type, all of these errors disappear. I have also not seen anay examples of functions returning non-built-in types either. These two facts lead me to believe that I may not be able to return object of a class I defined. So my question is whether it is possible to return an object from a class I have defined in Processing. If not, is there any way around this?
Here is my code:
class Complex {
int re, im; // real and imaginary components
Complex(int re, int im) {
this.re = re;
this.im = im;
}
}
Complex add(Complex x, Complex y) {
int re_new = x.re + y.re;
int im_new = x.im + y.im;
return new Complex(re_new, im_new);
}
With Processing just as with java you can return any object type with a function. Here's a short proof of concept for you to copy, paste and try:
void setup() {
Complex a = new Complex(1, 5);
Complex b = new Complex(2, 6);
Complex c = add(a, b);
println("[" + c.re + ", " + c.im + "]");
}
void draw() {
}
class Complex {
int re, im; // real and imaginary components
Complex(int re, int im) {
this.re = re;
this.im = im;
}
}
Complex add(Complex x, Complex y) {
int re_new = x.re + y.re;
int im_new = x.im + y.im;
return new Complex(re_new, im_new);
}
I noticed that the add
method light up as if it was shadowing another method, but it didn't prevent it to run as intended.
If the situation persists, you may want to post more code, as the problem may be somewhere unexpected. Good luck!