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.

0

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

java doesn't allow custom operator overloading. There is a built in overloading..
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.

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.