简体   繁体   中英

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.

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));

您甚至可以在那里实现类似的接口和覆盖compareTo方法

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM