Q: Please tell me more about the movements of lines 6 to 10 of UseBank.java.
1:public class Bank {
2—private int money;
3:public void setMoney(int money){
4—This.money=money;//Subtracts the number into the field
5: }
6:public int getMoney(){
7—return money;
8: }
9:}
1:public class UseBank{
2—public static void main (Steing[]args) {
3:// Instance Class Bank
4:Bank bank=new Bank();
5—int mny = Integer.parseInt(args[0]);
6:bank.setMoney(mny);
7:System.out.println("Transfer amount:"+mny);
8://bank.money=0;// Error Occurs
9: int nowMoney=bank.getMoney();
10:System.out.println("Current money:" + nowmoney;
11: }
12: }
>java Usebank 10000
Amount transferred: 10000
Current money: 10000
I made a diagram to make it easy to understand.Let's start with the third line.
I just ran the main, so there's nothing.(※ To be exact, the variable args
contains data about the parameters when the program was run, but is omitted in the diagram.)
Next, line 4, I'm making a bank here.
The Bank class has been initialized in the ↑bank variable.By the way, the blue part is private, so I can't see or touch it directly.
↑In the fifth line, the string "10000"
in args[0]
is converted into the variable mny
to the number 10000
.
↑ Line 7 sets 10000
to the money
variable of bank
through the setMoney
method.
↑ Finally, in line 9, the value of the money
variable in the bank
is copied to the nowMoney
variable through the getMoney
method.
Also, System.out.println
without explanation is a method for displaying results on the screen.
In the bank's money property, an instance of the Bank class created in line 4, the parse mny in line 5 is set (to put it simply, it's like substitution).
bank.setMoney(mny);
View mny in line 5.
System.out.println("Transfer amount:"+mny);
The money property of the bank instance has a private qualifier and cannot be accessed directly.
//bank.money=0;// Error Occurs
Get money for the bank instance through getter and initialize the variable nowMoney.
int nowMoney=bank.getMoney();
View nowMoney.
System.out.println("Current money:"+nowmoney);
© 2024 OneMinuteCode. All rights reserved.