Back to Using Objects

Lesson PreviewLesson 5 of 10 in this unit

2.4 Calling a Void Method with Parameters

Part of Using Objects in AP® Computer Science A. Read the opening section, then create a free account for the full interactive lesson, practice, and progress tracking.

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.

java
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 error
java
balance) {
        this.name = name;
        this.balance = balance;
    }

    // Private method to pay interest at 3%
    private void payInterest() {
        balance += balance * 0.03;
    }
}

Continue the full lesson in Stellar

Create a free account to unlock the remaining sections, checkpoints, course practice, and progress tracking for AP® Computer Science A.