1

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.

Anthea
  • 3,741
  • 5
  • 40
  • 64

4 Answers4

3

Java doesn't allow operator overdloading/overriding. You cannot do this.

Artem
  • 4,347
  • 2
  • 22
  • 22
  • 3
    java doesn't allow **custom** operator overloading. There is a built in overloading.. – amit Dec 21 '11 at 11:22
2

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. For Strings + 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.

Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
0

Java is not C++ you can't overload operators like '+' in Java

shift66
  • 11,760
  • 13
  • 50
  • 83
0

This cannot be done in java. If you are curious enough, check this post Why doesn't Java offer operator overloading? which excplains why it cannot be done and compares between java and c++ approaches

Community
  • 1
  • 1
Adel Boutros
  • 10,205
  • 7
  • 55
  • 89