Programming Tips - Java: How to override the = = operators in Java as I can in C++

Date: 2013oct22 Update: 2025oct13 Language: Java Q. Java: How to override the > < <= >= operators in Java as I can in C++ A. You can't but here is the next best thing. Override the equals() method and a compare() method as shown in this full example:
import java.util.Comparator; class Demo { static class MyClass implements Comparator<MyClass> { private int mData; public MyClass(final int in) { // Constructor mData = in; } @Override public boolean equals(Object obj) { return mData == ((MyClass)obj).mData; } @Override public int compare(MyClass a, MyClass b) { if (a.mData > b.mData) return 1; if (b.mData > a.mData) return -1; return 0; } } public static final void main(String[] args) { final MyClass one = new MyClass(1); final MyClass two = new MyClass(2); if (one.compare(two, one) >= 0) { System.out.println("two is greater than or equal to one"); } else { System.out.println("two is NOT greater than or equal to one"); } } }
Output:
two is greater than or equal to one