0

I know String is a final class in java.lang, so like string class is is possible to append other classes with the plus (+) operator.

For example I have a Class:

 public class Foo{
    public int x;
    public int y;
    public Foo(int x,int y){
       this.x=x;
       this.y=y;
    }
    public Foo append(int x,int y){
       return new Foo(this.x+x,this.y+y);
    }
 }

Now, is it possible to add two classes like this:

 Foo a=new Foo(2,3),b=new Foo(3,4);
 Foo c=a+b;
 System.out.println(c.x+"  "+c.y);

And get the output like this:

 5  7

If yes, what more will I have to do and if no why?

Aniruddha Sarkar
  • 1,903
  • 2
  • 14
  • 15

3 Answers3

5

It is called operator overloading and no, it is not possible in Java. Only classical methods are allowed.

Dici
  • 25,226
  • 7
  • 41
  • 82
2

No Java does not allow for operator overloading simply because it doesn't need it.

2.2.7 No More Operator Overloading There are no means provided by which programmers can overload the standard arithmetic operators. Once again, the effects of operator overloading can be just as easily achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables. Eliminating operator overloading leads to great simplification of code.

M A
  • 71,713
  • 13
  • 134
  • 174
  • 2
    "it doesn't need it" [citation needed] – Chris Martin Oct 18 '14 at 08:57
  • 2
    _`"simply because it doesn't need it"`_ - thats very opinion based, I enjoy that feature in C++ – msrd0 Oct 18 '14 at 08:57
  • Well, I think it would be nice for some classes to be able to overload the operators. Even for some built-in classes it could be useful, like for example the `*` operator for strings. However, I'll admit that it is not really necessary and that too much operators make the code unreadable (like in Scala, which I love anyway). – Dici Oct 18 '14 at 08:59
  • @manouti I think that rationale is crap, but you get an upvote for adding it :) – Chris Martin Oct 18 '14 at 09:03
  • The idea of being not needed is implied by the fact that it can be just as easily done without it, and without all of its potential complexities. Of course it is opinion based but it's a design decision. – M A Oct 18 '14 at 09:14
2

'for many years, the partly line from the Java team was "Operator overloading is too complicated." This and many other decisions where someone clearly didn't do their homework is why I have a reputation for disdaining many of the choices made by Gosling and the Java team' - Bruce Eckel in The Positive Legacy of C++ and Java

  • This could use a bit more context rather than just a pull-out quote which doesn’t answer the question directly. But it’s a nice little find. +1 for that. – Konrad Rudolph Oct 21 '14 at 20:46