Operator overloading and overriding in Java

后端 未结 5 1407
醉酒成梦
醉酒成梦 2020-11-29 13:25

What is the difference between operator overloading and operator overriding?

Are they the same in inheritance and console program?

相关标签:
5条回答
  • 2020-11-29 13:47

    You can overload operator in C++ but not in Java. I wonder if you meant method overloading and method overriding? Method overloading is having two definitions for the same method signature. For example,

    int sum(int var1, int var2)
    {
      return (var1+var2);
    }
    
    int sum(int var1, int var2, int var3)
    {
      return (var1+var2+var3);
    }
    

    In object oriented programming, you override (redefine) a function that is inherited from ascendant (base) class. In a class hierarchy, when a function (method) in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.

    0 讨论(0)
  • 2020-11-29 13:53

    There is no operator overloading/overriding in Java.

    0 讨论(0)
  • 2020-11-29 13:55

    Operator overloading and overriding are not supported in Java.

    Check following desc quoted from : http://java.sun.com/docs/white/langenv/Simple.doc2.html

    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.

    0 讨论(0)
  • 2020-11-29 13:55

    There is a javac-plugin (an annotation processor like Lombok) called "Java-OO", which adds operator overloading to Java.

    It allows you to add operator overloading to your own classes very easily. In addition to this, many of the built-in classes of the Java API also supports operator overloading when using this plugin. (For example: Instead of list.get(6) or map.get("hello") you can do list[6] and map["hello"])

    All you need to do is to include the .jar on the classpath when compiling with javac.

    There are plugins for all major IDEs: Eclipse, Netbeans and IntelliJ IDEA.

    0 讨论(0)
  • You cannot override (nor overload) operators in Java.

    In some other languages you can, and difference between operator overloading and overriding is the same like between function overloading and overriting. E.g. in Scala operators are just functions.

    0 讨论(0)
提交回复
热议问题