How do you create the return of a method that has the return type as the class? This is a method to find the sum of two numbers. The number object is created in another class, and it has to be added to the 'other' parameter. I am not sure if I am creating the method properly. And how would you create the proper return if the type is the class?
public class Number {
private double a;
private double b;
public Number (double _a, double _b) {
a = _a;
b = _b;
}
public Number sum(Number other) {
a = this.a + other.b;
b = this.b + other.b;
return ;
}
}
How do you create the return of a method that has the return type as the class?
The same way you handle any other use of a reference.
In your case you could just change your code to:
return this;
However, that's adding the given number to the existing one, mutating the object that you call the method on... a bit like StringBuilder.append
.
I suspect it would be better not to change either number, but instead create a new one:
public Number sum(Number other) {
return new Number(this.a + other.a, this.b + other.b);
}
(Currently you're not using other.a
at all, but I assume that was a typo.)
Aside from anything else, that way you can make your type immutable, which generally makes things easier to reason about. To do that, make the fields final
and make the class final
too. I would personally change the method name to plus
as well, but that's a matter of personal preference.
See more on this question at Stackoverflow