Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

class - "+" operator for Java-classes

I have a class like this:

private static class Num {
    private int val;

    public Num(int val) {
        this.val = val;
    }
}

Is it possible to add to objects of the class by using the "+"-operator?

Num a = new Num(18);
Num b = new Num(26);
Num c = a + b;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, you can't. + is overloaded only for numbers, chars and String, and you are not allowed to define any additional overloadings.

There is one special case, when you can concatenate any objects' string representation - if there is a String object in the first two operands, toString() is called on all other objects.

Here's an illustration:

int i = 0;
String s = "s";
Object o = new Object();
Foo foo = new Foo();

int r = i + i; // allowed
char c = 'c' + 'c'; // allowed
String s2 = s + s; // allowed
Object o2 = o + o; // NOT allowed
Foo foo = foo + foo; // NOT allowed
String s3 = s + o; // allowed, invokes o.toString() and uses StringBuilder
String s4 = s + o + foo; // allowed
String s5 = o + foo; // NOT allowed - there's no string operand

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...