Calling a Void Method with Parameters
In Java, the private keyword restricts access to a class's fields and methods. When declared as private, these members can only be accessed and modified by methods within the same class. You cannot directly interact with private members from outside the class.
We previously discussed the private keyword's role in restricting access to class fields. However, it's crucial to remember that the private keyword also applies to methods. This allows us to create methods that can only be called from within the class itself. The following example demonstrates the consequences of attempting to call a private method from outside the class.
public class Main {
public static void main(String[] args) {
BankAccount myAccount = new BankAccount("Stella R.", 7421.08);
myAccount.payInterest(); // Trying to call a private method outside the class
}
}Output
Main.java:5: error: payInterest() has private access in BankAccount
myAccount.payInterest(); // Trying to call a private method outside the class
^
1 errorbalance) {
this.name = name;
this.balance = balance;
}
// Private method to pay interest at 3%
private void payInterest() {
balance += balance * 0.03;
}
}