访问权限修改器是用于控制类、方法和属性的可见性的关键字。Java 中有四种访问权限修改器:
在以下代码中,我们将使用访问权限修改器来调整 withdraw
函数的访问权限:
public class BankAccount { private double balance; public BankAccount(double initialBalance) { balance = initialBalance; } // 将默认访问权限修改为 protected protected void withdraw(double amount) { balance -= amount; } // 保留 public 访问权限 public double getBalance() { return balance; } }
通过将 withdraw
函数的访问权限修改为 protected
,我们限制了从同一包外部对其的访问。它仍然可以从 BankAccount
类及其子类中访问,但不能从其他包中访问。
以下是展示如何使用 withdraw
函数的示例:
public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(1000.0); // 以下代码将报错,因为 withdraw() 函数不存在 public 访问权限 // account.withdraw(200.0); // 获取账户余额 double balance = account.getBalance(); System.out.println("账户余额:" + balance); } }
运行这段代码将输出:
账户余额:1000.0
如你所见,withdraw
函数无法从 Main
类中访问,但仍然可以从 BankAccount
类及其子类中访问。