0
Can we define what happens when operators are used along with Objects in Java?
I just wondered if we can tell operators like -, +, *, ^ and / when they are use with objects. Maybe even %. Expectation : class obj { --> whatever is required to start defining a behaviour, say subtraction Return obj1.val - (obj2.val*2); } obj A = new obj(); A.setVal(12); obj B = new obj(); B.setVal(3); S.o.print(A-B); //out-> 6 *** Please, there is no need to align your answers along my expectation. I would be just as eager to know what else can be done. Thank You
7 Respostas
+ 1
Yeah i heard about that. But my focus was more around the fact that String in not a DataType! It is an Object.
When we perform an action like:
"Value 1" + 1025;
Java interprets it as something similar to:
new StringBuilder("Value 1").concate(1025).toString();
So, can we define such a behaviour for other objects?
+ 1
Haha, nice zemiak. Well, then we have to use methods only!
+ 1
~ swim ~ , ok i get it.
+ 1
Thanks everyone
0
// this is joke
public class Obj {
int val;
int $ (Obj o) {return this.val + o.val;}; // + sum
int __ (Obj o) {return this.val - o.val;}; // - subtraction
public static void main(String[] args) {
Obj a=new Obj(), b=new Obj();
a.val = 30;
b.val = 20;
System.out.println( (a). $ (b) ); // 50
System.out.println( (a). __ (b) ); // 10
}
}