The Java language provides a lot of modifiers, mainly divided into the following two categories:
- Access modifier
- Non-access modifiers
Modifiers are used to define a class, method, or variable, usually at the head of the statement. We illustrate by the following example:
public class className { // ...
}
private boolean myFlag ; static final double weeks = 9 .5 ; protected static final int BOXWIDTH = 42 ; public static void main ( String [ ] arguments ) { // Method body }
private boolean myFlag ; static final double weeks = 9 .5 ; protected static final int BOXWIDTH = 42 ; public static void main ( String [ ] arguments ) { // Method body }
Access Control Modifiers
In Java, you can use access control characters to protect access to classes, variables, methods, and constructors. Java supports 4 different access rights.
- Default (ie default, nothing is written): visible in the same package without any modifiers. Use objects: classes, interfaces, variables, methods.
- Private : Visible within the same class. Use objects: variables, methods. Note: Can not modify the class (external class)
- Public : Visible to all classes. Use objects: classes, interfaces, variables, methods
- Protected : Visible to classes and all subclasses within the same package. Use objects: variables, methods. Note: You cannot decorate a class (external class) .
We can use the following table to illustrate access rights:
Modifiers | Current class | Within the same package | Descendants | Other packages | Other packages |
---|---|---|---|---|---|
public | Y | Y | Y | Y | Y |
protected | Y | Y | Y | N | Y/N ( description ) |
default | Y | Y | N | N | N |
private | Y | N | N | N | N |
Default Access Modifier - Do Not Use Any Keywords
Variables and methods declared with the default access modifier are visible to the classes in the same package. The interface where the variables are implicitly declared as public static Final , and the interface in the default access method as in the case public .
As shown in the following example, declarations of variables and methods can use no modifiers.
Examples
String version = " 1.5.1 " ;
boolean processOrder ( ) {
return true ;
}
Private access modifier -private
The private access modifier is the strictest access level, so methods, variables, and constructors that are declared private can only be accessed by the class they belong to, and classes and interfaces cannot be declared private .
Variables declared as private access types can only be accessed by external classes via public getter methods in the class.
The use of private access modifiers is mainly used to hide the implementation details of the class and protect the data of the class.
The following classes use private access modifiers:
public class Logger { private String format ;
public String getFormat ( ) {
return this . format ;
}
public void setFormat ( String format ) {
this.format = format ;
}
}
In the instance, the format variable in the Logger class is a private variable, so other classes cannot directly get and set the value of the variable. In order for other classes to be able to manipulate the variable, two public methods are defined: getFormat() (returning the value of format) and setFormat(String) (setting the value of format)
Public access modifier -public
Classes, methods, constructors, and interfaces that are declared as public can be accessed by any other class.
If several public classes that access each other are distributed in different packages, you need to import the package where the corresponding public class resides. Due to the inheritance of classes, all public methods and variables of a class can be inherited by its subclasses.
The following functions use public access controls:
public static void main ( String [ ] arguments ) { // ...
}
The main() method of a Java program must be set to public, otherwise the Java interpreter will not be able to run the class.
Protected access modifier -protected
Protected needs to be analyzed from the following two points:
- Subclasses and base classes are in the same package : Variables, methods, and constructors that are declared protected can be accessed by any other class in the same package;
- Subclasses and base classes are not in the same package : In a subclass, subclass instances can then access the protected methods inherited from the base class, but not the protected methods of the base class instance.
The protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared as protected, but interface member variables and member methods cannot be declared protected.
Subclasses can access methods and variables declared by the protected modifier, which protects unrelated classes from using these methods and variables.
The following parent class uses the protected access modifier, which overrides the parent's openSpeaker() method.
Class AudioPlayer {
protected boolean openSpeaker ( Speaker sp ) { // implementation details
}
}
class StreamingAudioPlayer extends AudioPlayer {
protected boolean openSpeaker ( Speaker sp ) {
// implementation details
}
}
If you declare the openSpeaker() method as private, classes other than AudioPlayer will not be able to access the method.
If you declare openSpeaker() as public, all classes have access to this method.
If we only want the method to be visible to the subclass of the class it is in, we declare the method as protected.
Protected is the most difficult to understand a Java class member access permission modifiers, more details please see the Java protected keyword explain .
Access Control and Inheritance
Please note the rules inherited by the following methods:
- The method declared as public in the parent class must also be public in the subclass.
- The methods declared as protected in the parent class are either declared as protected in the subclass or declared as public, and cannot be declared as private.
- Methods declared as private in the parent class cannot be inherited.
Non-access modifiers
In order to implement some other features, Java also provides many non-access modifiers.
The static modifiers are used to modify class methods and class variables.
The final modifier is used to modify classes, methods, and variables. Final modified classes cannot be inherited. Modified methods cannot be redefined by inherited classes. Modified variables are constants and cannot be modified.
The abstract modifier is used to create abstract classes and abstract methods.
The synchronized and volatile modifiers are mainly used for thread programming.
Static modifier
- Static variables:The static keyword is used to declare static variables that are independent of the object. No matter how many objects a class instantiates, its static variables have only one copy. Static variables are also called class variables. Local variables cannot be declared as static variables.
- Static method:The static keyword is used to declare static methods that are independent of the object. Static methods cannot use non-static variables of the class. The static method gets the data from the parameter list and then calculates the data.
Access to class variables and methods can be accessed directly using classname.variablename and classname.methodname .
As the following example shows, the static modifier is used to create class methods and class variables.
public class InstanceCounter {
private static int numInstances = 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 = 0 ; i < 500 ; ++ i ) {
new InstanceCounter ( ) ; }
System .out.println ( " the Created " +InstanceCounter.GetCount() + " instances ) ; }
}
System . out . println ( " Starting with " + InstanceCounter.getCount() + " instances " ) ; for( int i = 0 ; i < 500 ; ++ i ) {
new InstanceCounter ( ) ; }
System .out.println ( " the Created " +InstanceCounter.GetCount() + " instances ) ; }
}
The above example run edit results are as follows:
Starting with 0 instances Created 500 instances
Final modifier
Final variable:
The final variable can be explicitly initialized and can only be initialized once. A reference to an object declared as final cannot point to a different object. However, the data in the final object can be changed. In other words, the reference to the final object cannot be changed, but the value inside can be changed.
The final modifier is often used with the static modifier to create class constants.
Examples
public class Test {
final int value = 10 ;
// The following is an example of declaring a constant public static final int BOXWIDTH = 6 ; static final String TITLE = " Manager " ; public void changeValue ( ) {
value = 12 ; // an error will be output }
}
final int value = 10 ;
// The following is an example of declaring a constant public static final int BOXWIDTH = 6 ; static final String TITLE = " Manager " ; public void changeValue ( ) {
value = 12 ; // an error will be output }
}
Final method
The final methods in a class can be inherited by subclasses, but cannot be modified by subclasses.
The main purpose of declaring the final method is to prevent the contents of the method from being modified.
Use the final modifier to declare a method, as shown below.
public class Test {
public final void changeName ( ) { // Method body }
}
public final void changeName ( ) { // Method body }
}
Final class
The final class cannot be inherited. No class can inherit any of the features of the final class.
Examples
Public final class Test { // body
}
Abstract modifier
Abstract class:
An abstract class cannot be used to instantiate an object. The sole purpose of declaring an abstract class is to extend it in the future.
A class cannot be modified by both abstract and final. If a class contains an abstract method, then the class must be declared as an abstract class, otherwise a compilation error will occur.
Abstract classes can contain abstract methods and non-abstract methods.
Examples
abstract class Caravan { private double price ;
private String model ;
private String year ;
public abstract void goFast ( ) ; // abstract method
public abstract void changeColor ( ) ;
}
Abstract method
An abstract method is a method without any implementation. The concrete implementation of this method is provided by subclasses.
Abstract methods cannot be declared final and static.
Any subclass that inherits from an abstract class must implement all abstract methods of the parent class unless the subclass is also an abstract class.
If a class contains several abstract methods, the class must be declared as an abstract class. Abstract classes can contain no abstract methods.
The abstract method declaration ends with a semicolon, for example: public abstract sample(); .
Examples
public abstract class SuperClass {
abstract void m ( ) ; // abstract method }
class SubClass extends SuperClass { // implement abstract methods Void m ( ) { ......... }
}
abstract void m ( ) ; // abstract method }
class SubClass extends SuperClass { // implement abstract methods Void m ( ) { ......... }
}
Synchronized modifier
The synchronized keyword declaration method can only be accessed by one thread at a time. The synchronized modifier can be applied to four access modifiers.
Examples
public synchronized void showDetails ( ) {
.......
}
Transient modifier
When the serialized object contains an instance variable that has been transient-modified, the java virtual machine (JVM) skips that particular variable.
This modifier is included in the statement that defines the variable and is used to preprocess the data type of the class and variable.
Examples
public transient int limit = 55 ; // will not be persistent
public int b ; // persistent
Volatile modifier
A volatile decorated member variable is forced to re-read the value of the member variable from shared memory each time it is accessed by a thread. Also, when a member variable changes, it forces the thread to write the change back to shared memory. So at any moment, two different threads always see the same value of a member variable.
A volatile object reference may be null.
Examples
public class MyRunnable implements Runnable {
private volatile boolean active ; public void run ( ) {
active = true ; while ( active ) // first line { // code }
}
public void stop ( ) {
active = false ; // second line }
}
private volatile boolean active ; public void run ( ) {
active = true ; while ( active ) // first line { // code }
}
public void stop ( ) {
active = false ; // second line }
}
Normally, a thread calls the run() method (the thread that is started in Runnable) and the stop() method is called in another thread. If the first line of active value in the buffer is used, then the second row cycle does not stop when the active is false.
However, in the above code we use volatile to modify active, so the loop will stop.
Comments
Post a Comment