Access level modifiers. Access modifiers
Here we will try to consider almost all cases of applying access modifiers. The exception will be only their use for nested ( nested.) and internal ( inner) Classes, as well as for interfaces, as these topics we have not yet considered.
Classes and packages are used in conjunction with access modifiers serve as encapsulation by means of concealing the implementation details by simple interface.
Access modifiers can be applied to both classes and their members - fields and methods. In total, there are four access modifiers and here we will bring their brief description, then consider each in detail.
- public - any component declared as public, Available from any code
- protected. - Allows access to the component within the package and classes of heirs
- private - allows access to the component within the class
- default (no keyword) - allows access to components within the package
Heirs classes are classes inherited from any class. Inheritance, we have not yet studied.
Access to classes
The default top-level classes are available in the package in which they are defined.. However, if the top-level class is declared as public, It is available everywhere (or everywhere where the package itself is available). We limited this approval by top-level classes, because classes can be announced as members of other classes. Since these internal classes are members of the class, then they are subject to the rules for monitoring access to members of the class.
Access to class members
Class members are always available inside the body body. Default Class members are also available in a package in which the class is defined..
Public modifier
For a class that is not embedded, only one of the two possible access levels can be specified: specified default and public . When the class is declared as public, he must be the only public The class declared in the file and the file name must match the class name.
how public Classes, fields, methods and designers can be announced.
Modifier Protected.
We will consider this modifier in detail in the subject of inheritance of classes. If inheritance is not used, then this modifier works, as well as the default modifier.
The only thing that can be briefly said that the components declared as protected.will have access any child class from any package Or any class from the same package.
how protected. Fields, methods, designers, invested classes and nested interfaces can be announced.
protected. .
Private modifier
It is the most hard to limit access modifier. Elements announced as private Available only within the same class and anyone outside the class.
how private Fields, methods, designers, embedded classes and nested intrefes can be announced.
Classes and upper level interfaces can not be announced as private .
Essentially, access modifiers are a simple topic, but we will also return to it. While it was just acquaintance. And now a little practice ...
I created the classes mod02.java, defmod.java, promod.java and prvmod.java which belong to the Pro.java.pkg002 package, as well as class pubmod.java, belonging to the Pro.java.pkg003 package. Next, I will bring simply screenshots of these classes and the result of the program:
Hey! In today's lecture, we will get acquainted with the concept " access modifiers"And consider examples of working with them. Although the word "get acquainted" will not be quite correct: with most of them you are already familiar to previous lectures. Just in case, refreshing the main thing in memory. Access modifiers - These are most often keywords that regulate the level of access to different parts of your code. Why "most often"? Because one of them is set by default and is not denoted by a key word :) In total, Java has four access modifiers. We list them in order from the stringent to the most "soft":
- private;
- protected;
- dEFAULT (Package Visible);
- public.
Private modifier
![](https://i1.wp.com/javarush.ru/images/article/6a8c0181-8bbe-442e-b040-c74c62501986/1024.jpeg)
Modifier Protected.
The next strictness of access modifier is Protected.![](https://i2.wp.com/javarush.ru/images/article/8d4b98ea-fbf8-4bd6-89ff-7447166ab7c7/1024.jpeg)
- within all classes located in the same package as our;
- within all the characters of the heirs of our class.
Package Visible modifier
Further, our list is the Default modifier or, as it is also called, Package Visible. It is not denoted by a key word, since it is installed in the default Java for all fields and methods. If you write in your code - int x \u003d 10 ... The X variable will be this most Package Visible access. Remember what it does, easy. In fact, Default \u003d Protected -Nore :) Cases of its application are limited, as well as the modifier Protected. Most often, Default means is used in the package, where there are some kind of utility classes that do not implement the functionality of all other classes in this package. Let us give an example. Imagine that we have a package " services." Inside it there are various classes that work with the database. For example, there is a USERSERVICE class, reading user data from the database, the Carservice class, reading from the same database of cars, and other classes, each of which works with its type of objects and reads data about them from the base. Package Services; Public Class Userservice () Package Services; Public Class Carservice () However, the situation may easily happen when data in the database is in one format, and we need them in another. Imagine that the date of the user's date in the database is stored in TimeStamp WITH TIME ZONE ... 2014 - 04 - 04 20: 32: 59.390583 + 02 ... We need the easiest object - java.util.date. For this purpose, we can create inside the Special Class of Mapper inside the SERVICES package. It will be responsible for converting data from the base in our usual Java objects. Simple auxiliary class. Usually we create all classes like Public Class Classname, but it is not necessary. We can declare our auxiliary class just like Class Mapper. In this case, he still does his job, but not visible to anyone outside the service pack! Package Services; Class Mapper () Package Services; Public Class Carservice (MAPPER MAPPER;) And this is, in fact, the correct logic: why someone outside the package see an auxiliary class working only with classes of the same package?Public modifier
And the last on the list, but not significantly - the Public modifier! With him, you met on the first day of study on Javarush, first in my life running the Public Static Void Main (String Args).![](https://i1.wp.com/javarush.ru/images/article/4323b90c-193c-444c-88e4-cfd8af695107/1024.jpeg)
The Java language provides many modifiers divided into the following categories:
- access modifier
- Non-access modifier
The modifier is used to determine the class, method or variable, as a rule, on the front edge of the application. Through the following example for illustration:
Public Class Classname (// ...) Private Boolean MyFlag; STATIC FINAL DOUBLE WEEKS \u003d 9.5; PROTECTED STATIC FINAL INT BOXWIDTH \u003d 42; Public Static Void Main (String Arguments) (// 方法方法)
Access control modifier
Java, you can use access control characters to protect access to classes, variables, methods and designers. Java supports four different access rights.
By default, also known as the value default Visible in the same packet, do not use any modifier.
Private to indicate private Modifier visible within the same class.
There is, in order to indicate common The modifier visible for all classes.
Protected, B. protected The modifier determines that for all classes and subclasses within the same package visible.
Default Access Modifier - Do not use any keywords
Use variables and methods declared in the default access modifier for a class within the same package is visible. The interface where the variables are implicitly declared as a public static finals, and an interface where the default access method for the public.
The application in the following example, variables and methods cannot use any modifier.
STRING VERSION \u003d "1.5.1"; Boolean ProcessOrder () (Return True;)
Private access modifier -Private
The private access modifier is the most stringent level of access, it is declared both private methods, variables, and belongs to the class of the constructor can be available only, and classes and interfaces cannot be declared closed.
Variables declared as a private access type can be available only outside the class through the class of the public heter method.
Modifier Private access is mainly used for the class of protection of the details of the implementation and data data.
The following classes use a private access modifier:
Public Class Logger (Private String Format; Public String GetFormat () (Return this.Format;) Public Void SetFormat (String Format) (this.format \u003d format;))
Example, variable Logger class format is a private variable, so that other classes cannot directly receive and set the value of the variable. In order to be able to work from another variable of the class, the two open methods are determined: getFormat () (return value) and SetFormat (String) (format setting)
Open access modifier -pobric
It is declared as public classes, methods, designers, and interfaces can be any other access type.
If several mutual visits of public classes in different packages, you need to import the corresponding package of the public class is constantly located. Since the inheritance of classes, the class of all publicly available methods and variables can be inherited by its subclasses.
The following functions use public access control:
Public Static Void Main (String Arguments) (// ...)
The main Java program () must be installed in public places, otherwise, the Java interpreter will not be able to start the class.
Protected Access Modifiers Protected
It is declared as protected variables, methods and constructors in the same package can be any other access type, and can be available in various subclass packages.
Protected access modifier cannot be changed classes and interfaces, methods and member variables can be declared both protected, but interface member methods cannot be declared protected.
modifier Subclasses can access secure methods and variables, so that we can protect unbound classes using these methods and variables.
The next parent class uses a secure access modifier, subclasses override the OpenSpeaker () method of the parent class.
Class Audioplayer (SPEAKER SP) (// 实现)) Class Streamingaudioplayer (Boolean OpenSpeaker (SPEAKER SP) (// 实现 细节))
If the OpenSpeaker () method is declared as private, then in addition to the class Audioplayer can not access the method. If OpenSpeaker () is announced as public, then all classes have the ability to access the method. If we want to make the process visible for class subclasses, the method is declared as protected.
Access control and inheritance
Pay attention to the following methods inherited the rules:
The parent class is declared as public methods in the subclass must also be public.
The parent class is declared as a secure method in a subclass or declared as protected, or announced publicly. You can not be declared closed.
The parent class is declared as a private method cannot be inherited.
Non-access modifier
In order to achieve a number of other functions, Java also provides a number of modifiers without access.
static modifier is used to create class methods and class variables.
The final modifier used to decorate classes, methods and variables, the final modified class cannot be inherited, the modified class method cannot be inherited overridden, modified constant variable, cannot be changed.
The abstract modifier is used to create abstract classes and abstract methods.
Synchronous and volatile modifiers, mainly for programming threads.
Static modifier
Static variables:
Static Using the keyword to declare static variables that do not depend on the object, regardless of how many objects of the class instance, it is only one copy of the static variable. Static variables are also known as class variables. Local variables cannot be declared as static variables.
Static methods:
A static keyword is used to declare an object does not depend on the static method. Static methods cannot use a static variable class. Static method to get data from the list of parameters, and then calculate the data.
Access to class variables and methods can be used directly to Classname.variablelename and classname.methodname access.
In the following example, the static modifier is used to create class methods and class variables.
Public Class InstanceCounter (Private Static Int Numinstances \u003d 0; Protected Static Int GetCount () (Return Numinstances;) Private Static Void AddInstance () (NuminstanceS ++;) InstanceCounter () (InstanceCounter.addinstance ();) Public Static Void Main (String Arguments ) (System.out.printLN ("Starting WITH" + instancecounter.getcount () + "instances"); for (int i \u003d 0; i< 500; ++i){ new InstanceCounter(); } System.out.println("Created " + InstanceCounter.getCount() + " instances"); } }
Examples of the above results of editing operation as follows:
Started With 0 Instances Created 500 Instances
Final classifier
Finite variables:
Final variables can be explicitly initialized and initialized only once. The directory is declared as end objects cannot specify another object. But the ultimate goal, where data can be changed. This ultimate reference to the object cannot be changed, but the value of which can be changed.
The final modifier is usually used together to create a static modifier class constant.
Public Class Test (Final int Value \u003d 10; // 下面 是 声声 常量 的 实例 Public Static Final Int BoxWidth \u003d 6; Static Final String title \u003d "(! Lang: Manager"; public void changeValue(){ value = 12; //将输出一个错误 } } !}
Final method
Methods The final class is inherited by subclasses, but cannot change subclasses.
The main purpose of the method is to prevent the final statement of this method varies.
As will be shown below, using finite methods of declaration modifiers.
Public Class Test (Public Final Void ChangeName () (// 方法方法))
Final category
End classes cannot be inherited, no class can inherit any of the characteristics of the final class.
Public Final Class Test (// 类类)
Abstract modifier
Abstract class:
The abstract class cannot be used to create an object instance, the sole purpose of the application is an abstract class for the future expansion of this class.
The class cannot be changed abstract and final. If the class contains abstract methods, the class must be declared as an abstract class, otherwise, the compiler error.
An abstract class may contain abstract methods and not abstract methods.
Abstract Double Price; Private String Model; Private String Year; Public Abstract Void Gofast (); // 抽象 Public Abstract Void ChangeColor ();)
Abstract method
No method is an abstract implementation of the method, the specific implementation of the method of subclasses provided. Abstract methods cannot be declared as final and strict.
Any subclass inherits an abstract class must implement all the abstract parent-class methods, if the subclass is not an abstract class.
If the class contains a number of abstract methods, the class must be declared as an abstract class. An abstract class cannot contain abstract methods.
The abstract announcement of the method ends with a semicolon, for example: a public abstract sample ();
Public Abstract Class SuperClass (Abstract Void M (); // 抽象 方法) Class Subclass Extends SuperClass (// 实现 抽象 方法 Void M () (.........))
Synchronous modifier
Method Synchronous keyword to declare the same time only one thread access. The synchronous modifier can be applied to the four access modifiers.
Public Synchronized Void ShowDetails () (.......)
Transition modifier
The serialized object contains modified by the transition variable instance of the Java virtual machine (JVM) to skip this specific variable.
The modifier is enabled in the definition of application variables for pre-processing data types and variables.
Public Transient int limit \u003d 55; // Will Not Persist Public Int B; // Will Persist.
Volatile modifiers
The volatile modified member variable every time you turn to it streams are forced to re-read the value of a member variable from the shared memory. In addition, when changes in variable members, the stream is forced to change the value is recorded back in the overall memory. So at any time, two different topics always see the same member variable value.
Public Class MyRunnable Implements Runnable (Private Volatile Booolean Active; Public Void Run () (Active \u003d True; While (Active) // 第一 (// 代码)) Public Void Stop () (Active \u003d False; // 第二 行))
Under normal circumstances, the flow causes the () RUN (in the Runnable open stream) in another call stream to stop () method. If active value in first line buffer is used, in second row when the active cycle is false does not stop.
Nevertheless, the above code, we use a modified volatile active, so the cycle will stop.
Last updated: 04/20/2018
All class members in the Java - fields and methods - have access modifiers. In previous topics, we have already encountered the Public Modifier. Access modifiers allow you to set a permissible scope for class members, that is, a context in which this variable or method can be used.
Java uses the following access modifiers:
public: Public, publicly available class or class member. The fields and methods declared with the Public modifier are visible to other classes from the current package and out of external packets.
private: a closed class or class member, the opposite of Public modifier. A closed class or class member is available only from the code in the same class.
protected: Such a class or class member is available from anywhere in the current class or package or in derived classes, even if they are in other packages
Default modifier. The lack of a modifier in a field or class method involves the default modifier to it. Such fields or methods are visible to all classes in the current packet.
Consider access modifiers using the example of the following program:
Public Class Program (Public Stating Void Main (String Args) ("Kate", 32, "Baker Street", "+12334567"); kate.displayname (); // norms, Public Kate method. displayage (); // norms, the method has a default modifier kate.displayphone (); // norms, the PROTECTED //KATE.DISPLAYADDRESS () method; //! Error, Private System.Out.PrintLN method (kate.name) ; // Norm, default modifier System.out.printLN (kate.address); // Norm, Public System.Out.printLN modifier (kate.age); // Norm, modifier PROTECTED //SYSTEM.Out.PrintLN ( kate.phone); //! Error, Private)) Class Person (String Name; Protected Int Age; Public String Address; Private String Phone; Public Person (String Name, Int Age, String Address, String Phone) (this. name \u003d name; this.age \u003d age; this.address \u003d address; this.phone \u003d phone;) public void displayName () (System.out.printf ("name:% s \\ n", name);) void displayage () (System.out.Printf ("Age:% D \\ N", Age);) Private Void D isplayaddress () (System.out.Printf ("address:% s \\ n", address); ) PROTECTED VOID DisplayPhone () (System.out.printf ("Phone:% S \\ N", Phone);))
In this case, both classes are located in one package - the default package, so in the Program class we can use all methods and variables of the Person class, which have a modifier for the intction, Public and Protected. And the fields and methods with the Private modifier in the Program class will not be available.
If the Program class would have been located in another package, only fields and methods with the Public modifier would be available to him.
The access modifier must precede the rest of the variable definition or method.
Encapsulation
It would seem why not to declare all variables and methods with the Public modifier so that they are available at any point of the program regardless of the package or class? Take, for example, the AGE field, which represents age. If another class has direct access to this field, it is likely that in the process of the program, it will be transmitted incorrect value, for example, a negative number. This data change is not desirable. Or we want some data to be worthwhile directly so that they can be displayed on the console or simply recognize their meaning. In this regard, it is recommended to restrict data access as much as possible to protect them from unwanted access from outside (both to get the value and changes). The use of various modifiers ensures that the data will not be distorted or changed is not properly changed. Similar data hiding inside a certain area of \u200b\u200bvisibility is called encapsulation.
So, as a rule, instead of direct use of fields, as a rule, use access methods. For example:
Public Class Program (String Args) (Person Kate \u003d New Person ("Kate", 30); System.out.printLN (kate.getage ()); // 30 kate.setage (33); System .out.PrintLN (kate.getage ()); // 33 kate.setage (123450); System.out.printLN (kate.getage ()); // 33)) Class Person (Private String Name; Private Int Age ; Public Person (String Name, Int AGE) (this.name \u003d name; this.age \u003d age;) Public String GetName () (Return this.name;) Public Void SetName (String Name) (this.name \u003d name; ) public int getage () (Return this.age) Public Void Setage (IF AGE) (IF (Age\u003e 0 && Age< 110) this.age = age; } }
And then instead of direct operation with the Name and Age fields in the Person class, we will work with the methods that set and return the values \u200b\u200bof these fields. SETNAME, SETAGE methods are also called mutator, as they change the field values. And the GETNAME methods, getage and likely called Accessor, since with their help we get the field value.
And in these methods, we can invest additional logic. For example, in this case, when you change the age, it is checked as far as the new value corresponds to the permissible range.
Last updated: 03.10.2019
All class members - fields, methods, properties - they all have access modifiers. Access modifiers allow you to set a permissible scope for class members. That is, access modifiers determine the context in which you can use this variable or method. In previous topics, we already encountered it when the fields of the class were announced (that is, with the Public modifier).
The following access modifiers are applied in C #:
public: Public, publicly available class or class member. Such a class member is available from anywhere in the code, as well as from other programs and assemblies.
private: Closed class or class member. Represents the complete opposite of the Public modifier. Such a closed class or class member is available only from the code in the same class or context.
protected: Such a class member is available from anywhere in the current class or in derived classes. In this case, derived classes can be located in other assemblies.
iNTERNAL: Class and class members with a similar modifier are available from any source code in the same assembly, however it is not available for other programs and assemblies (as in the case of the Public Modifier).
pROTECTED INTERNAL: combines the functionality of two modifiers. Classes and members of a class with such a modifier are available from the current assembly and from derived classes.
private Protected: Such a class member is available from anywhere in the current class or in derived classes that are defined in the same assembly.
We can explicitly set the access modifier, for example:
Private Protected Class State (Protected Void Print () (Console.Writeline ($ "a \u003d (a)");))
Or we can not indicate:
Class State (int a; void print () (Console.WriteLine ($ "a \u003d (a)");))
If the Access Modifier is not defined for fields and methods, the default Private modifier is used for them.
Classes and structures declared without a modifier have the default access to Internal.
All classes and structures defined directly in namespaces and are not embedded in other classes, only Public or Internal modifiers can have.
Let's look at the example and create the following class state:
Public Class State (// Still that Private In DefaultVar; int defaultvar; // The field is available only from the current class Private INT PrivateVar; // Available from the current class and derived classes that are defined in the same project Protected Private INT ProtectedPrivateVar; // Available from the current class and derivatives Protected int ProtectedVar; // Available anywhere in the current project Internal int InternalVar; // Available anywhere in the current project and from heirs' classes in other projects Protected Internal Int ProtectedInternalVar; // Available in Any place of the program, as well as for other programs and builds Public int publicvar; // By default, the Private Void DefaultMethod () \u003d\u003e Console.Writeline modifier () \u003d\u003e Console.Writeline ($ "DEFAULTVAR \u003d (DefaultVar)"); // Method is available only from the current class Private void PrivateMethod () \u003d\u003e Console.Writeline ($ PrivateVar \u003d (PrivateVar)); // Available from current class and derived classes that are defined in the same Rosect Protected Private void ProtectedPrivateMethod () \u003d\u003e Console.Writeline ($ PROTECTEDPRIVATEVAR \u003d (PROTECTEDPRIVATEVAR) "); // Available from the current class and derivatives Protected Void ProtectedMethod () \u003d\u003e Console.WriteLine ($ "ProtectedVar \u003d (Protectedvar)"); // Available anywhere in the current project INTERNAL VOID INTERNALMETHOD () \u003d\u003e CONSOLE.WRITELINE ($ "INTERNALVAR \u003d (INTERNALVAR)"); // Available anywhere in the current project and from the heir classes in other projects Protected Internal Void ProtectedInternalmethod () \u003d\u003e Console.Writeline ($ ProtectedInternalVar \u003d (ProtectedInternalvar) "); // Available anywhere in the program, as well as for other programs and builds Public void publicmethod () \u003d\u003e Console.Writeline ($ "PublicVar \u003d (PublicVar)"); )
Since the state class is declared with the Public Modifier, it will be available from any place of the program, as well as from other programs and assemblies. The State class has five fields for each access level. Plus one variable without a modifier that is closed (Private) by default.
There are also six methods that will display the values \u200b\u200bof the class fields on the screen. Note that since all modifiers allow you to use class members within this class, then all class variables, including closed, are available to all its methods, since everyone is in the context of the class class.
Now let's see how we can use the variables of our class in the program (that is, in the Main class of the Program class), if the State and Program classes are in one project:
Class Program (Static Voide1 \u003d New State (); // Assign the value of the variable defaultvar, we will not work, // Since it has a Private modifier and the Program class does not see it // and this string environment will emphasize as wrong state1.defaultvar \u003d 5; // Error, access can not // The same applies to the privatevar state1.privatevar \u003d 5; // Error, access cannot be available // Assign the value of the variable ProtectedPrivateVar will not work, // Since the Program class is not a class-heir class state state1.protectedPrivateVar \u003d 5; // Error, access cannot be available // Assign the value of the variable ProtectedVar will not work either, // Since the Program class is not a class-heir class State state1.protectedVar \u003d 5; // Error, access cannot be available // The InternalVar variable with the Internal modifier is available from anywhere in the current project // Therefore, we quietly assign it the value of state1.internalvar \u003d 5; // ProtectedInternalVar variable is also available from any place of the current project state1.protectedInternalVar \u003d 5; // PublicVar variable publicly available state1.publicvar \u003d 5; ))
Thus, we were able to install only the variables of InternalVar, ProtectedInternalvar and PublicVar, as their modifiers allow you to use in this context.
The situation is similar and with the methods:
Class Program (Static Voide1 \u003d New State (); state1.defaultMethod (); // Error, access cannot be accessed by state1.privatemethod (); // Error, access cannot be accepted state1.protectedPrivateMethod () ; // Error, access cannot be accessible state1.protectedMethod (); // Error, access cannot be accessible state1.internalmethod (); // norms state1.protectedInternalmethod (); // STATE1.PUBlicMethod () norm; // norm))
Here we also have access to only three methods: INTERNALMETHOD, PROTECTEDInternalmethod, publicmethod, which are available, according to the Internal modifiers, Protected Internal, Public.
Thanks to such a system of access modifiers, you can hide some points of the class from other parts of the program.
Despite the fact that Public and Internal modifiers are similar in their actions, but they have a great difference. Class and class members with the Public modifier will also be available to other programs if the data is made in the DLL dynamic library and then use it in these programs.