Javase Getting Started learning 10:java modifiers

Source: Internet
Author: User
Tags modifiers

The Java language provides a number of modifiers, mainly divided into the following two categories:

access modifiers

non-access modifiers

Modifiers are used to define a class, method, or variable, usually at the front end of a statement. We use the following example to illustrate:

<span style= "FONT-SIZE:18PX;" >public class ClassName {   //...} Private Boolean flag;static final double weeks = 9.5;protected static final int boxwidth = 42;public static void Main (Stri Ng[] args) {   //method body}</span>

an access control modifier

In Java, you can use access controls to protect access to classes, variables, methods, and construction methods. Java supports 4 different kinds of access rights.

A default, also known as default, is visible within the same package and does not use any modifiers.

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

c public, specified with the publicly modifier, visible to all classes.

D is protected, specified with the protected modifier, visible to classes and all subclasses within the same package.

(1) Default access modifier-do not use any keywords

Variables and methods declared with the default access modifier are visible to classes within the same package. The variables in the interface are implicitly declared as public static

Final, and the method in the interface is public by default.

Instance:

As the following example shows, the declarations of variables and methods may not use any modifiers.

<span style= "FONT-SIZE:18PX;" >string Version = "1.5.1"; Boolean ProcessOrder () {   return true;</span>

(1) Private access modifier-private

Private access modifiers are the most restrictive access level, so methods, variables, and construction methods that are declared private can only be accessed by the owning class, and the class

and interfaces cannot be declared as private.

A variable declared as a private access type can only be accessed by an external class through a public getter method in the class.

The use of the private access modifier is primarily used to hide the implementation details of the class and to protect the class's data.

The following class uses the private access modifier:

<span style= "FONT-SIZE:18PX;" >public class Logger {   private String format;   Public String GetFormat () {      return this.format;   }   public void SetFormat (String format) {      This.format = format;   }} </span>

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. To enable other classes to

Manipulating the variable, defines two public methods: GetFormat () (returns the value of format) and SetFormat (String) (sets the value of format).

(3) public access modifier-public

Classes, methods, construction methods, and interfaces that are declared public can be accessed by any other class.

If several publicly accessed public classes are distributed in unused packages, you need to import the package that contains the appropriate public class. Because of the inheritance of classes, all classes

Public methods and variables can be inherited by their subclasses.

The following functions use public access control:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >public static void Main (string[] arguments) {   //...} </span></span>

The main () method of the Java program must be set to public, otherwise the Java interpreter will not be able to run the class.

(4) Protected access modifier-protected

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

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

cannot be declared as protected.

Subclasses can access the 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, and the subclass overloads the Openspeaker () method of the parent class.

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >class Audioplayer {   protected Boolean openspeaker (Speaker sp) {      //implementation details   }}} class Streamingaudioplayer Extends Audioplayer  {   boolean openspeaker (Speaker sp) {      //implementation Details   }}</span></span>

If the Openspeaker () method is declared private, classes other than Audioplayer will not be able to access the method. If you put

Openspeaker () is declared public, all classes have access to the method. If we only want the method to be visible to subclasses of its class, the

The method is declared as protected.

(5) Access control and inheritance

Note the following methods inherit the rule:

a method declared as public in a parent class must also be public in the subclass.

A method declared as protected in a parent class is either declared as protected in the subclass, or declared as public. cannot be declared as private.

The method that is declared by the default modifier in the C parent class, which can be declared as private in the subclass.

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

two non-access modifiers

Java also provides a number of non-access modifiers in order to implement some other functionality.

1) Static modifier, used to create class methods and class variables.

2) The final modifier, used to modify classes, methods, and variables, the final decorated class cannot be inherited, the decorated method cannot be redefined by the inheriting class,

The variable of the decoration is a constant and is not modifiable.

3) abstract modifier, used to create abstract classes and abstract methods.

4) Synchronized and volatile modifiers, primarily for threading programming.

(1) static modifier

A static variable

The static keyword is used to declare static variables that are independent of an object, regardless of how many objects a class instantiates, and its static variables have only one copy. Static

Variable is also a class variable. Local variables can be declared as static variables

B static Method:

The static keyword is used to declare an object-independent method. Static methods cannot use non-static variables of a class. Static method gets the number from the argument list

And then calculate the data.

Access to class variables and methods can be accessed directly using Classname.variablename and Classname.methodname.

The static modifier is used to create class methods and class variables, as shown in the following example.

<span style= "FONT-SIZE:18PX;" >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 < i++) {         new Instancecounter ();      }      System.out.println ("Created" +      Instancecounter.getcount () + "instances");}   } </span>

The above example runs the editing result as follows:

<span style= "FONT-SIZE:18PX;" >started with 0 instancescreated instances</span>
(2) final modifier

1) Final variable:

The final variable can be explicitly initialized and initialized only once. A reference to an object that is declared final cannot point to a different object. But the final

The data in the elephant can be changed. This means that the final object reference cannot be changed, but the value inside can be changed.

The final modifier is typically used with the static modifier to create a class constant.

Instance:

<span style= "FONT-SIZE:18PX;" >public class test{  final int value = ten;  The following is an instance of declaring a constant public  static final int boxwidth = 6;  Static final String TITLE = "Manager";   public void ChangeValue () {     value = 12;//will output an error  }}</span>

2) Final method

The final method in the class can inherit from the quilt class, but cannot be modified by the quilt class.

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

Declare the method with the final modifier, as shown below.

<span style= "FONT-SIZE:18PX;" >public class test{public    final void ChangeName () {       //method body    }}</span>
3) Final class

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

Instance:

<span style= "FONT-SIZE:18PX;" >public Final class Test {   //class body}</span>

(3) abstract modifier

A abstract class

An abstract class cannot be used to instantiate an object, and the sole purpose of declaring an abstract class is to augment the class in the future.

A class cannot be both abstract and final decorated. If a class contains an abstract method, the class must be declared as an abstract class, otherwise the

Translation errors.

Abstract classes can contain both abstract and non-abstract methods.

Instance:

<span style= "FONT-SIZE:18PX;" >abstract class caravan{   private double price;   private String model;   Private String year;   public abstract void Gofast (); Abstract method public   abstract void ChangeColor ();} </span>
B Abstract Method

An abstract method is a method that does not have any implementation, and the specific implementation of the method is provided by the subclass. Abstract methods cannot be declared as final and strict.

Any child class that inherits an abstract class must implement all the 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 declaration of an abstract method ends with a semicolon, for example: Public abstract sample ();

Instance:

<span style= "FONT-SIZE:18PX;" >public abstract class superclass{abstract    void m ();//Abstract method}  class Subclass extends superclass{     // Implement abstract method      void m () {          ...      }} </span>

(4) Synchronized modifier

The method of synchronized keyword declaration can only be accessed by one thread at a time. The synchronized modifier can be applied to four access modifiers.

Instance:

<span style= "FONT-SIZE:18PX;" >public synchronized void ShowDetails () {...} </span>
(5) transient modifier

When a serialized object contains an instance variable that is transient decorated, the Java Virtual Machine (JVM) skips that particular variable.

The modifier is included in the statement that defines the variable, which is used to preprocess the data type of the class and variable.

Instance:

<span style= "FONT-SIZE:18PX;" >public transient int limit =;   would not persistpublic int b; Would persist</span>

(6) Volatile modifier

A volatile-modified member variable forces the value of the member variable to be reread from shared memory each time it is accessed by the thread. Also, when a member variable occurs

When changing, forcing a thread to write changes back to shared memory. So at any moment, two different threads always see the same value for a member variable.

A volatile object reference may be null.

Instance:

<span style= "FONT-SIZE:18PX;" >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    } }</span>
In General, call the Run () method in one thread and call the Stop () method in another thread. If the value of the active in line 1 in the buffer is

When you set the active in line 2 to False, the loop does not stop.

Javase Getting Started learning 10:java modifiers

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.