我们这里有一个 JavaBean 类——BankAccount.java,以及一个测试类——Test.java
public class BankAccount{
private double balance; //账户余额
public BankAccount(){
balance = 0;
}
public BankAccount(double initMoney){
balance = initMoney;
}
//存款方法
public void deposit(double nums){
balance = balance + nums;
}
//取款方法
public void withdraw(double nums){
if(balance >= nums)
balance = balance - nums;
}
//获取账户余额
public double getBalance(){
return balance;
}
}
public class Test{
public static void main(String[] args){
BankAccount bankAccount = new BankAccount();
bankAccount.deposit(1000);
bankAccount.withdraw(400);
System.out.println(bankAccount.getBalance().toString());
}
}
我们都知道,每创建一个BankAccount类的对象,都有一个和这个对象相对应的实例字段 balance。而我们每次通过 BankAccount 对象调用 BankAccount 类中的公有方法去操作实例字段时,Java 编译器是通过什么去把对象和实例字段相对应呢?
其实这里面就有一个隐式参数的概念了。调用方法时的显示参数我们都知道,就是方法括号中的参数值;而隐式参数就是调用该方法的对象了。
我把方法改造一下就会更明白了:
BankAccount bankAccount1 = new BankAccount();
bankAccount1.deposit(1000);
BankAccount bankAccount2 = new BankAccount();
bankAccount2.deposit(1000);
当 bankAccount1 对象调用 deposit 方法时,deposit 方法是这样的:
//存款方法
public void deposit(double nums){
bankAccount1.balance = bankAccount1.balance + nums;
}
当 bankAccount2 对象调用 deposit 方法时,deposit 方法是这样的:
//存款方法
public void deposit(double nums){
bankAccount2.balance = bankAccount2.balance + nums;
}
所以说它是通过隐式参数去操作对应的实例字段的,而隐式参数就是调用该方法的对象。
而隐式对象也可以不用直接用对象名去表示,也可以通过 this 关键字,如下:
public void deposit(double nums){
this.balance = this.balance + nums;
}
this 就是代表调用该方法的当前对象。
还有一种特殊现象,就是构造方法之间相互调用,上面的构造方法也可以改成如下:
public BankAccount(){
this(0);
}
public BankAccount(double initMoney){
balance = initMoney;
}
第一个构造方法中的 this(0); 就是调用的另一个构造方法;构造方法中的 this 调用是构造方法之间的相互调用,而并不是指当前对象。