Java modifier and java Modifier

Source: Internet
Author: User

Java modifier and java Modifier

The Java language provides many modifiers, mainly divided into the following two types:

  • Access Modifier
  • Non-access modifier

Modifiers are used to define classes, methods, or variables. They are usually placed at the front of the statement. The following example is used to describe:

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}
Access Control Modifier

In Java, access controllers can be used to protect access to classes, variables, methods, and constructor methods. Java supports four different access permissions.

Default, also known as default, is visible in the same package without any modifiers.

Private, specified with a private modifier, visible within the same class.

Public modifier, which is visible to all classes.

Protected, specified with the protected modifier, and visible to classes and all subclasses in the same package.

Default access modifier-No keywords are used

Variables and Methods declared using the default access modifier are visible to classes in the same package. All the variables in the interface are implicitly declared as public static final, and the access permission of the methods in the interface is public by default.

Instance:

As shown in the following example, variables and methods can be declared without any modifiers.

String version = "1.5.1";boolean processOrder() {   return true;}
Private access modifier-private

The private access modifier is the strictest access level. Therefore, methods, variables, and constructor declared as private can only be accessed by their classes, and classes and interfaces cannot be declared as private.

Variables declared as private access can only be accessed by external classes through the public getter method in the class.

The use of the Private access modifier is mainly used to hide the implementation details of the class and protect the class data.

The following class uses a private access modifier:

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 this variable. To allow other classes to operate on this variable, two public methods are defined: getFormat () (return format value) and setFormat (String) (set format value)

Public access modifier-public

Classes, methods, constructor methods, and interfaces declared as public can be accessed by any other class.

If several public classes are distributed in different packages, You need to import the packages where the corresponding public classes are located. Because of the inheritance of the class, all the public methods and variables of the class can be inherited by its subclass.

The following functions use public access control:

public static void main(String[] arguments) {   // ...}

The main () method of the Java program must be set to public. Otherwise, the Java interpreter cannot run this class.

Protected access modifier-protected

Variables, methods, and constructors declared as protected can be accessed by any other class in the same package, or by sub-classes in different packages.

The Protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared as protected, but the member variables and member methods of the interface cannot be declared as protected.

Subclass can access the methods and variables declared by the Protected modifier, so as to protect irrelevant classes from using these methods and variables.

The following parent class uses the protected access modifier, And the subclass overload the openSpeaker () method of the parent class.

Class AudioPlayer {protected boolean openSpeaker (Speaker sp) {// Implementation Details} class StreamingAudioPlayer {boolean openSpeaker (Speaker sp) {// Implementation Details }}

If you declare the openSpeaker () method as private, classes other than AudioPlayer cannot access this method. If openSpeaker () is declared as public, all classes can access this method. If we only want this method to be visible to the subclass of its class, declare this method as protected.

Access Control and inheritance

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 method declared as protected in the parent class is declared as protected or public in the subclass. Cannot be declared as private.

  • The method declared as private in the parent class cannot be inherited.

Non-access modifier

To implement some other functions, Java also provides many non-access modifiers.

Static modifier used to create class methods and class variables.

The Final modifier is used to modify classes, methods, and variables. The final modifier class cannot be inherited, the modifier method cannot be redefined by the inherited class, And the modifier variable is a constant, it cannot be modified.

Abstract modifier, used to create Abstract classes and Abstract methods.

Synchronized and volatile modifiers are mainly used for Thread Programming.

Static Modifier
  • Static variables:

    The Static keyword is used to declare Static variables independent of objects. No matter how many objects a class instantiates, its Static variables have only one copy. Static variables are also considered class variables. Local variables can be declared as static variables.

  • Static Method:

    Static keywords are used to declare Static methods independent of objects. Static methods cannot use non-static variables of classes. The static method obtains data from the parameter list and then computes the data.

You can directly use classname. variablename and classname. methodname to access class variables and methods.

As shown in the following example, 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("Created " +      InstanceCounter.getCount() + " instances");   }}

The preceding instance running editing result is as follows:

Started with 0 instancesCreated 500 instances
Final Modifier

Final variable:

Final variables can be explicitly initialized and can only be initialized once. Objects declared as final cannot be referenced to different objects. However, the data in the final object can be changed. That is to say, the reference of the final object cannot be changed, but the value in it can be changed.

The Final modifier is usually used with the static modifier to create class constants.

Instance:

Public class Test {final int value = 10; // The following example declares the 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 method in the class can be inherited by the quilt class, but cannot be modified by the quilt class.

The main purpose of declaring the final method is to prevent the content of the method from being modified.

Use the final modifier to declare the method, as shown below.

Public class Test {public final void changeName () {// method body }}
Final class

The Final class cannot be inherited, and no class can inherit any features of the final class.

Instance:

Public final class Test {// class body}
Abstract Modifier

Abstract class:

Abstract classes cannot be used to instantiate objects. The sole purpose of declaring an abstract class is to expand the class in the future.

A class cannot be modified simultaneously by abstract and final. If a class contains an abstract method, the class must be declared as an abstract class; otherwise, a compilation error occurs.

Abstract classes can contain abstract and non-abstract methods.

Instance:

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 specific implementation of this method is provided by the subclass. Abstract methods cannot be declared as final or strict.

Any subclass that inherits the abstract class must implement all abstract methods of the parent class, unless this 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 not contain abstract methods.

The declaration of an abstract method ends with a semicolon, for example, public abstract sample ();

Instance:

Public abstract class SuperClass {abstract void m (); // abstract method} class SubClass extends SuperClass {// implements the abstract method void m () {.........}}
Synchronized Modifier

The method declared by the Synchronized keyword can only be accessed by one thread at a time. The Synchronized modifier can be applied to four access modifiers.

Instance:

public synchronized void showDetails(){.......} 
Transient Modifier

When a serialized object contains an instance variable modified by transient, the Java Virtual Machine (JVM) skips this specific variable.

This modifier is included in the statements defining variables and used to pre-process the data types of classes and variables.

Instance:

public transient int limit = 55;   // will not persistpublic int b; // will persist
Volatile Modifier

Each time a member variable modified by Volatile is accessed by a thread, the value of the member variable is forcibly re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory. In this way, two different threads always see the same value of a member variable at any time. A volatile object reference may be null.

Instance:

Public class MyRunnable implements Runnable {private volatile boolean active; public void run () {active = true; while (active) // line 1 {// code} public void stop () {active = false; // line 2 }}

Generally, the run () method is called in one thread and the stop () method is called in another thread. If the value of active in line 1 in the buffer is used, the loop will not stop when the value of active in line 2 is set to false.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.