【发布时间】:2014-12-13 19:12:33
【问题描述】:
我知道 String 是 java.lang 中的 final 类,所以像 string 类一样可以用加号 (+) 运算符附加其他类。
例如我有一个类:
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);
}
}
现在,是否可以像这样添加两个类:
Foo a=new Foo(2,3),b=new Foo(3,4);
Foo c=a+b;
System.out.println(c.x+" "+c.y);
得到这样的输出:
5 7
如果是,我还需要做什么?如果不是,为什么?
【问题讨论】:
-
Foo c = a.append(b.x, b.y) -
我知道我可以使用它,这就是我包含该命令但我想使用 + 运算符执行相同功能的原因
-
我相信 C++ 有这个功能,为什么在 java 中没有呢?
-
因为 C++ 和 Java 是两种不同的语言,选择可能不同
-
另外,您可以问:为什么不能定义一个名为
+的方法,为什么不能使用中缀表示法调用方法(就像在 Scala 中一样)。
标签: java operator-keyword addition