There are four access permission modifiers in Java: public (access from anywhere), protected (access to the same package, sub-package and sub-class), package access (access to the same package) and private (access only to the class), Can control the visibility of classes, interfaces, and methods.
Example analysis of access modifiers for Java functions
Access modifiers specify the visibility of classes, interfaces and methods sexual level. In Java, there are the following four access modifiers:
Practical case:
Suppose we have a Bank
class, which has a getAccountBalance
method for Get account balance. We want this method to be accessible only through the Bank
class outside the Account
class.
public class Bank { private Account account; public Account getAccount() { return account; } public double getAccountBalance() { return account.getBalance(); } } class Account { private double balance; public double getBalance() { return balance; } }
In the above example, the getAccountBalance
method is declared as public
, which means it can be accessed outside the Bank
class. However, the getBalance
method is declared as private
, which means it can only be accessed within the Account
class. Therefore, external classes cannot directly access the balance information of the Account
class.
Usage Notes:
The above is the detailed content of Example analysis of access permission modifiers for Java functions. For more information, please follow other related articles on the PHP Chinese website!