I'd like to perform equivalency and boolean tests quickly on my Java instances. How I do the equivalent of the Python3 code in Java? (notice that there is no reference to any attribute - just the instance itself)
test.py
class Number:
def __init__(self,n):
self.n = n
def __eq__(self, num):
return self.n == num
def __bool__(self):
return True
def main():
t = Number(10)
if t == 10:
print("Equivalency")
if t:
print("Boolean")
if __name__ == "__main__":
main()
Output
$ python3 test.py
Equivalency
Boolean
You cannot override ==
, nor can you implement a __bool__
equivalent. However, you most definitely should override equals()
(and probably hashCode()
as well). This equals method will be used by everything to compare object equality. The only time you would use ==
is if you wanted to see if two variables were pointing to the same object in memory.
@Override
public boolean equals(Object other) {
...
}