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

26th Nov 2019, 3:58 PM
Anirudh Sharma
Anirudh Sharma - avatar
7 Réponses
+ 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?
26th Nov 2019, 4:15 PM
Anirudh Sharma
Anirudh Sharma - avatar
+ 1
Haha, nice zemiak. Well, then we have to use methods only!
27th Nov 2019, 2:08 AM
Anirudh Sharma
Anirudh Sharma - avatar
+ 1
~ swim ~ , ok i get it.
27th Nov 2019, 2:09 AM
Anirudh Sharma
Anirudh Sharma - avatar
+ 1
Thanks everyone
27th Nov 2019, 2:09 AM
Anirudh Sharma
Anirudh Sharma - avatar
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 } }
26th Nov 2019, 9:58 PM
zemiak