Java中的运算符重载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1686699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:35:47  来源:igfitidea点击:

Operator overloading in Java

javaoperator-overloading

提问by Vipul

Please can you tell me if it is possible to overload operators in Java? If it is used anywhere in Java could you please tell me about it.

请您告诉我是否可以在 Java 中重载运算符?如果它在 Java 中的任何地方使用,请告诉我。

采纳答案by Jon Skeet

No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.

不,Java 不支持用户定义的运算符重载。Java 唯一接近“自定义”运算符重载的方面是对字符串的 + 处理,这会导致常量的编译时连接或使用 StringBuilder/StringBuffer 的执行时连接。但是,您无法定义自己的操作符,它们的行为方式相同。

For a Java-like (and JVM-based) language which doessupport operator overloading, you could look at Kotlinor Groovy. Alternatively, you might find luck with a Java compiler plugin solution.

对于其中一个Java类(和基于JVM)语言支持操作符重载,你可以看看科特林Groovy的。或者,您可能会在Java 编译器插件解决方案中找到运气。

回答by Brian Agnew

You can't do this yourself since Java doesn't permit operator overloading.

您不能自己执行此操作,因为 Java 不允许运算符重载。

With oneexception, however. +and +=are overloaded for String objects.

不过,有一个例外。++=为 String 对象重载。

回答by teabot

Operator overloading is used in Java for the concatenation of the String type:

Java 中使用运算符重载来串联 String 类型:

String concat = "one" + "two";

However, you cannotdefine your own operator overloads.

但是,您不能定义自己的运算符重载。

回答by rob

Java does not allow operator overloading. The preferred approach is to define a method on your class to perform the action: a.add(b)instead of a + b. You can see a summary of the other bits Java left out from C like languages here: Features Removed from C and C++

Java 不允许运算符重载。首选方法是在您的类上定义一个方法来执行操作:a.add(b)而不是a + b. 您可以在此处查看 Java 从 C 类语言中遗漏的其他部分的摘要:从 C 和 C++ 中删除的功能

回答by MSalters

In addition to all the people pointing out that +is overloaded for Strings, -is also overloaded for both floating point and integer operations, as are *and /.

除了所有人都指出+对字符串-重载之外,对于浮点和整数运算也都重载了,就像*和 一样/

[edit] %is also overloaded for floating point, which can be a bit of a surprise for those with a C or C++ background.

[edit] %也为浮点重载,这对于有 C 或 C++ 背景的人来说可能有点意外。

回答by Alexander Mironov

One can try Java Operator Overloading. It has its own limitations, but it worth trying if you really want to use operator overloading.

可以尝试Java Operator Overloading。它有其自身的局限性,但如果您真的想使用运算符重载,则值得一试。

回答by Aurelien B

Just use Xtend along with your Java code. It supports Operator Overloading:

只需将 Xtend 与您的 Java 代码一起使用。它支持运算符重载:

    package com.example;

@SuppressWarnings("all")
public class Test {
  protected int wrapped;

  public Test(final int value) {
    this.wrapped = value;
  }

  public int operator_plus(final Test e2) {
    return (this.wrapped + e2.wrapped);
  }
}

package com.example

class Test2 {

    new() {
        val t1 = new Test(3)
        val t2 = new Test(5)
        val t3 = t1 + t2
    }

}

On the official website, there is a list of the methods to implement for each operator !

官网上有每个运营商要实现的方法列表!

回答by alknows

Or, you can make Java Groovyand just overload these functions to achieve what you want

或者,您可以制作 Java Groovy并重载这些功能来实现您想要的

//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...

class Fish {
    def leftShift(Fish fish) {
        print "You just << (left shifted) some fish "
    }
}


def fish = new Fish()
def fish2 = new Fish()

fish << fish2

Who doesnt want to be/use groovy? :D

谁不想成为/使用 groovy?:D

No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.

不,您不能以相同的方式在 Java 中使用已编译的 groovy JAR。它仍然是 Java 的编译器错误。

回答by Fernando Pelliccioni

As many others have answered: Java doesn't support user-defined operator overloading.

正如许多其他人所回答的那样:Java 不支持用户定义的运算符重载。

Maybe this is off-topic, but I want to comment on some things I read in some answers.

也许这是题外话,但我想评论我在一些答案中读到的一些内容。

About readability.
Compare:

关于可读性。
相比:

  1. c = a + b
  2. c = a.add(b)
  1. c = a + b
  2. c = a.add(b)

Look again!
Which one is more readable?

再看!
哪个更易读?

A programming language that allows the creation of user-defined types, should allow them to act in the same way as the built-in types (or primitive types).

允许创建用户定义类型的编程语言应该允许它们以与内置类型(或原始类型)相同的方式运行。

So Java breaks a fundamental principle of Generic Programming:
We should be able to interchange objects of built-in types with objects of user-defined types.
(You may be wondering: "Did he say 'objects of built-in'?". Yes, see here.)

所以 Java 打破了泛型编程的一个基本原则:
我们应该能够将内置类型的对象与用户定义类型的对象互换。
(您可能想知道:“他说的是‘内置对象’吗?”。是的,请参阅此处。)

About String concatenation:

关于字符串连接:

Mathematicians use the symnol + for commutative operations on sets.
So we can be sure that a + b = b + a.
String concatenation (in most programming languages) doesn't respect this common mathematical notation.

数学家使用符号 + 对集合进行交换运算。
所以我们可以确定 a + b = b + a。
字符串连接(在大多数编程语言中)不遵守这种常见的数学符号。

a := "hello";
b := "world";
c := (a + b = b + a);
a := "hello";
b := "world";
c := (a + b = b + a);

or in Java:

或在 Java 中:

String a = "hello";
String b = "world";
boolean c = (a + b).equals(b + a);
String a = "hello";
String b = "world";
boolean c = (a + b).equals(b + a);

Extra:
Notice how in Java equality and identity are confused. The == (equality) symbol means:
a. Equality for primitive types
b. Identity-check for user-defined types, therefore, we are forced to use the functionequals() for equality.
But... What has this to do with operator overloading?
If language allows operator overloading the user could give the proper meaning to the equality operator.

额外:
注意 Java 中的相等性和同一性是如何混淆的。==(相等)符号表示:
a. 原始类型的相等性
b.用户定义类型的身份检查,因此,我们被迫使用函数equals() 进行相等。
但是……这与运算符重载有什么关系?
如果语言允许运算符重载,则用户可以为相等运算符赋予正确的含义。

回答by nayanjyoti sharma

Unlike C++ , Java does not support user defined operator overloading . The overloading is done internally in java ,We can take +(plus) for ex: int a=2+4; , string="hello"+"world"; Here plus adds two integer numbers and concatenate two strings. So we can say that Java supports internal operator overloading but not user defined.

与 C++ 不同,Java 不支持用户定义的运算符重载。重载是在java内部完成的,我们可以取+(plus) for ex: int a=2+4; , string="你好"+"世界"; 这里 plus 将两个整数相加并连接两个字符串。所以我们可以说Java支持内部运算符重载但不支持用户定义。