Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using operators with objects in Java

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.

like image 430
sdoganay Avatar asked Aug 20 '15 09:08

sdoganay


People also ask

What is object operators in Java?

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

How do you create an object using a new operator?

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.

What is && and || in Java?

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.

What does *= mean in Java?

The multiplication assignment operator ( *= ) multiplies a variable by the value of the right operand and assigns the result to the variable.


2 Answers

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

like image 84
eric.m Avatar answered Sep 20 '22 22:09

eric.m


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));
like image 40
Suresh Atta Avatar answered Sep 21 '22 22:09

Suresh Atta