Java 17 Recipes
-1. Controlling Access to Members of a Class
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
5-1. Controlling Access to Members of a Class
Problem You want to create members of a class that are not accessible from any other class. Solution Create private instance members rather than making them available to other classes (public or protected). For instance, suppose you are creating an application to manage a team of players for a sport. You create a class named Player that represents a player on the team. You do not want the fields for that class to be accessible from any other class. The following code demonstrates the declaration of some instance members, making them accessible only from within the class in which they were defined. private String firstName; private String lastName; 152 private String position; private int status = -1; How It Works To designate a class member as private, prefix its declaration or signature using the private keyword. The private access modifier hides members of a class so that outside classes cannot access them. Any members of a class marked as private are available only to other members of the same class. Any outside class cannot access fields or methods designated as private, and an IDE that uses code completion cannot see them. As mentioned in the solution to this recipe, three different access modifiers can be used when declaring members of a class. Those modifiers are public, protected, and private. Members that are declared as public are available for any other class. Those declared as protected are available for any other class within the same package and subclasses. It is best to declare public or protected only those class members that need to be directly accessed from another class. Hiding members of a class using the private access modifier helps to enforce better object-orientation. Moreover, a default scope is accessible from the package and the class— that occurs when it is not assigned scope to a class element. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling