0

How do I access method of an object from another object of the same class?

I'm building a Mobile Money System using Java. The program is running fine but I want to send money from one object (user) to another object(user) by accessing the deposit method of object one(receiver) from object two(sender). Can someone help please?

8th Aug 2021, 4:51 PM
Maxwell D. Dorliea
Maxwell D. Dorliea - avatar
4 Answers
+ 1
here's a generic class to get the idea across: class MyClass{ private num; public static void main(String[] args){ MyClass my_account = new MyClass(50); MyClass your_account = new MyClass(20); your_account.transfer(my_account, 30); } public MyClass(int num){ this.num = num; } public transfer(MyClass to, int amount){ to.num += amount; num -= amount; } } Though as @Ipang said, realistically these methods should be supplied through the API you're working with (unless you're building the server/app pair from scratch, there should be some sort of API supplied to interface with the bank's servers, where the bank's programs do their "thing somewhere in between"). Now, I haven't added a check to this at all (usually you check the balance first before transferring), but I did so for the sake of conciseness. Hope this helps in some way.
8th Aug 2021, 7:18 PM
BootInk
BootInk - avatar
+ 2
By the conventional way, that is the bank's responsibility to manage the process. So for example, I can't just magically transfer money to my sister without the bank doing its thing somewhere in between, right?
8th Aug 2021, 4:56 PM
Ipang
+ 1
void sendMoney( Customer receiver, int amount) { //.. receiver.getMoney(amount); }
8th Aug 2021, 7:45 PM
zemiak
+ 1
Thanks Alot BootInk zemiak
8th Aug 2021, 10:08 PM
Maxwell D. Dorliea
Maxwell D. Dorliea - avatar