0

I've made a Vector class in java and i would like to be able to add 2 Vectors like this and get an answer: vector1 + vector2 how can i define in code that whenever a Vector type is added to another Vector type it will perform a certin calculation and return it?

Opl Itay
  • 39
  • 1
  • 5
  • 5
    Java does *not* support *operator overloading*. https://www.sololearn.com/Discuss/268580/why-does-java-not-support-user-define-operator-overloading/ – Willem Van Onsem Feb 16 '18 at 09:45
  • 1
    You cannot do `v1 + v2` like that. You'll have to create an `add` method in the class and do it like `v1.add(v2)` – denvercoder9 Feb 16 '18 at 09:45
  • @WillemVanOnsem didn't know _operator overloading_ is a thing. Does any other language support it? – denvercoder9 Feb 16 '18 at 09:46
  • 1
    @rafid059: yes, C++, Python, C#, Haskell, ... But in my opinion (except for Haskell since it is a functional programming language), most of these operator overloading features tend to produce horrible programs, since it is harder to understand what function will actually perform the operator call. Yes, there can be good reasons to do it, but very frequently, it introduces an additional layer of complexity which makes it more error prone. – Willem Van Onsem Feb 16 '18 at 09:47
  • 1
    https://stackoverflow.com/questions/77718/why-doesnt-java-offer-operator-overloading – Willem Van Onsem Feb 16 '18 at 09:48
  • @WillemVanOnsem thanks ! – denvercoder9 Feb 16 '18 at 09:49
  • I think Kotlin does it well. Try that as an alternative to Java. – duffymo Feb 16 '18 at 13:03

0 Answers0