Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Implement Operators in a Java Class

Tags:

java

operators

I am attempting to create a unsigned integer class.

public class UnsignedInteger extends Number implements Comparable<UnsignedInteger> 
    { 
    ... 
    }

Is there a way to implement operators such as; +, -, *, /, <<, >>, |, ^, >>>, <<

like image 245
Jay Tomten Avatar asked Feb 12 '13 14:02

Jay Tomten


2 Answers

Java does not support Operator Overloading. The only option you have is define methods like add(), subtract(), multiply(), etc, and write the logic there, and invoke them for particular operation.

You can have a look at BigInteger class to get an idea of how you can define methods to support various operations. And if interested, you can even go through the source code, that you can find in the src folder of your jdk home directory.

like image 183
Rohit Jain Avatar answered Oct 26 '22 10:10

Rohit Jain


There are already 5 answers saying that you cannot overload operators, but I want to point out that you can not use arithmetical operators on objects at all. They only work with primitive types (int, double, etc).

The only reason the following code compiles

Integer a = 1, b = 2;
Integer c = a + b;

is because the Java compiler compiles it as

Integer a = Integer.valueOf(1), b = Integer.valueOf(2);
Integer c = Integer.valueOf(a.intValue() + b.intValue());

If you want this to work for your UnsignedInteger, you have to extend the javac (it is possible, though).

like image 29
Cephalopod Avatar answered Oct 26 '22 12:10

Cephalopod