Let's say we have a class as follows:
public class Time{
int hour;
int min;
Time(int hour,int m){
hour=h;
min=m;
}
public String toString(){
return hour+":"+min;
}
}
And I want to write some code like this in main with results as in the comments:
Time t1 = new Time(13,45);
Time t2= new Time(12,05);
System.out.println(t1>=t2); // true
System.out.println(t1<t2); // false
System.out.println(t1+4); // 17:45
System.out.println(t1-t2); // 1:40
System.out.println(t1+t2); // 1:50 (actually 25:50)
System.out.println(t2++); // 13:05
Can I do that by interfaces etc. or the only thing I can do is to write methods instead of using operators?
Thanks in advance.
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
The multiplication assignment operator ( *= ) multiplies a variable by the value of the right operand and assigns the result to the variable.
That's called operator overloading, which Java doesn't support: Operator overloading in Java
So yes, you have to stick with methods.
EDIT: As some comments have said, you can implement Comparable to make your own compareTo method https://stackoverflow.com/a/32114946/3779214
You simply cannot. You cannot overload an operator. You need to write methods in to supports those operators.
Instead of writing methods in Time, I suggest you to write util methods.
For ex:
System.out.println(TimeUtil.substract(t1,t2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With