I wonder if there is a way to make an own conversion to integer in java. I mean a solution that is comparable to the implementation of the string conversion (toString). I want my class to be interpreted as integer in equation without calling a special function.
class MyClass(){
private int number;
MyClass(int n){
this.number = n;
}
public int toInteger(){
return number
}
}
usage:
MyClass a = new MyClass(2);
int result = 1+a;
result would be 3.
You’re describing operator overloading, and it’s not possible in Java. The closest thing would be subclassing Number, but
+doesn’t work with it. ForStrings+works because it has been built in as a special case in the language. There’s no way to extend+to work with anything else.Of course, with your class,
int result = 1 + a.toInteger();works. Just a little extra work.