6

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.

sdoganay
  • 63
  • 1
  • 5

5 Answers5

5

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

Community
  • 1
  • 1
eric.m
  • 1,577
  • 10
  • 20
3

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));
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can even implement comparable interface and override compareTo method there

SacJn
  • 777
  • 1
  • 6
  • 16
1

Operator overloading is not supported in Java. (It can be obfuscating and doesn't work well for reference-based languages: even the humble == causes a lot of confusion with Java object references).

For some of the methods you want to implement, the idiomatic way in Java to do what you want is to implement Comparable<T>. Then (1) your methods will be conventional, and (2) you'll be able to store instances of your class in sets and tree maps.

For other operations, such as the subtraction, write a function subtract. Think carefully what this should return. Should it be a time, or a time interval? I also question the validity of adding two time objects.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Java does not allows Operator overloading (here). But you can add some functionallity to your class like muliply(Time t) and write it manually. To compare your Classes you can integrate the Comparable-Interface which let you add the needed Functionallity to compare two Classes.

Community
  • 1
  • 1
MrT
  • 594
  • 2
  • 17