Java modifier details

Source: Internet
Author: User

The Java language defines the six common modifiers public, protected, Private, abstract, static, and final.
Five frequently-used modifiers are also defined. The following describes the 11 Java modifiers:
1. Public
Objects used: classes, interfaces, and members
Introduction: No matter where the package is defined, this class (interface, member) is accessible.
2. Private
Intended audience: Members
Introduction: A member can only be accessed in the class that defines it.
3. Static
Object used: Class, method, field, initialization Function
Introduction: an internal class named static is a top-level class, which is irrelevant to the members of the class. Static Method
Is a class method,
Is to be directed to the class rather than the instance of the class. A static field is a class field.
Number of instances.
Only one instance is pointed to the class rather than the instance of the class. The initialization function is executed when the class is loaded.
Instead of creating
Executed when the instance is running.
4. Final
Objects used: classes, methods, fields, and variables
Description: A class defined as final cannot contain child classes, cannot be overwritten (cannot be used for dynamic queries), and field values.
Not Allowed
Modify.
5. Abstract
Objects used: classes, interfaces, and methods
Description: classes include methods that are not implemented and cannot be instantiated. If it is an abstract method, the method body
Null.
The implementation of the method is defined in the subclass, and the class that contains an abstract method must be an abstract class.
6. Protected
Intended audience: Members
Introduction: A member can only be accessed in the defined package. If it is accessed in another package, the class that implements this method
It must be
Subclass of the member's class.
7. Native
Intended audience: Members
Description: it is related to the operating platform. Its method is not defined when it is defined. The implementation of the method is implemented by an external library.
8. strictfp
Objects used: classes and Methods
Introduction: all methods in the strictfp modifier class hide the strictfp modifier and all floating points of method execution.
Computing compliance
IEEE 754 standard. All values, including intermediate results, must be of the float or double type, but cannot be used.
Floating by local platforms
The extra precision or representation range provided by the point format or hardware.
9. Synchronized
Usage object: Method
Introduction: For a static method, JVM locks the class in which it belongs before execution. For a non-static class
Method, execution
Before locking a specific object instance.
10. Volatile
Use object: Field
Introduction: Because the asynchronous thread can access fields, some optimization operations cannot be applied to fields.

Volatile modifier variable. Every time a thread is accessed, 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.
Let's look at the example in Java language specification.
Condition: A thread continuously calls Method One (), and a thread continuously calls method two (). I have tested it many times and it seems that this situation has never occurred.

Code
Class test {
Static int I = 0, j = 0;
Static void one () {I ++; j ++ ;}
Static void two (){
System. Out. println ("I =" + I + "J =" + J );
}
}

Occasionally, J is greater than I. Because the method is not synchronized, I and j may not be updated once. One way to prevent this is to declare two methods as synchronized.

Code
Class test {
Static int I = 0, j = 0;
Static synchronized void one () {I ++; j ++ ;}
Static synchronized void two (){
System. Out. println ("I =" + I + "J =" + J );
}
}

This prevents two methods from being executed at the same time, and ensures that J and I are updated at the same time, so that the values of I and j are always the same.
Another way is to declare I and j as volatile.

Code
Class test {
Static volatile int I = 0, j = 0;
Static void one () {I ++; j ++ ;}
Static void two (){
System. Out. println ("I =" + I + "J =" + J );
}
}
Volatile sometimes
Synchronized can be replaced.
11. Transient
Use object: Field
Description: fields are not part of the object's persistent State and should not be concatenated with objects.

Transient is a variable modifier marked as transient. These variables are not serialized when an object is serialized.

For example, if the member variable of a class is transient, the value of the transient variable will not be saved when an instance of this class is saved to the disk through objectoutputstream.

When the object is serialized and stored in the memory, some field data is not expected to be saved. To ensure security, you can declare these fields as transient.

For more information, see the serialized content.

-------------------------------------------------------

 

 

The Java language specifies that, if there is no modifier for the class in the same package, the default package permission is used and the class in the package can be accessed. However, this is not accurate enough. Specifically, only the class loaded by the same classloader has the above package permissions.
[Keyword] javaclassloader package

To gain an in-depth understanding of the classloader mechanism of Java, we will first do the following experiment:

Package java. Lang;

Public class test {

Public static void main (string [] ARGs ){

Char [] C = "1234567890". tochararray ();

String S = new string (0, 10, c );

}

}

The string class has a constructor string (INT offset, int length, char [] array) with the package permission. According to the default access permission, test belongs to Java. lang package. Therefore, we should be able to access the string constructor theoretically. Compiled! The execution result is as follows:

Exception in thread "Main" Java. Lang. securityexception: prohibited package name:

Java. Lang

At java. Lang. classloader. defineclass (unknown source)

At java. Security. secureclassloader. defineclass (unknown source)

At java.net. urlclassloader. defineclass (unknown source)

At java.net. urlclassloader. Access $100 (unknown source)

At java.net. urlclassloader $ 1.run( unknown source)

At java. Security. accesscontroller. doprivileged (native method)

At java.net. urlclassloader. findclass (unknown source)

At java. Lang. classloader. loadclass (unknown source)

At sun. Misc. launcher $ appclassloader. loadclass (unknown source)

At java. Lang. classloader. loadclass (unknown source)

At java. Lang. classloader. loadclassinternal (unknown source)

Strange? To find out why securityexception occurs, you must understand the classloader mechanism.

Java classloader is used to dynamically load classes. classloader loads a class only once. There are four types of classloader used by JVM:

Start the class loader, standard extension class loader, class path loader, and network class loader.

The priorities of these four classloader types are from high to low. The so-called "parent-parent Delegation Model" is used ". Specifically, if a Network Class Loader is requested to load a java. lang. integer. It will first send the request to the class path loader at the upper level. If the returned result is loaded, the Network Class Loader will not load this java. lang. integer. If the class path loader at the upper level returns not loaded, it will load Java. lang. integer.

Similarly, after receiving the request (whether directly requesting loading or uploading the next-level classloader), the class path loader will first send the request to the standard extension class loader at the upper-level, in this way, the class loader has the highest priority if it finds Java in its own way. lang. the following classloader cannot load Java. lang. integer, although you write a java. lang. integer, trying to replace the Java of the core library. lang. integer is impossible, because the class you write cannot be loaded by the lower-layer classloader.

Let's talk about the package permission. The Java language specifies that, if there is no modifier for the class in the same package, the default package permission is used and the class in the package can be accessed. However, this is not accurate enough. Specifically, only the class loaded by the same classloader has the above package permissions. For example, the start class loader loads java. Lang. string, and the class path loader loads java. Lang. Test Written by ourselves. They cannot access each other's methods with package permissions. This prevents malicious code from accessing the package permission method of the core class.

 

Ava is not perfect. Java is far slower than traditional C ++ in terms of running speed. Java cannot directly access the underlying operating system (such as system hardware ), therefore, Java uses the native method to extend the functions of Java programs.
The native method can be compared to the interface of a Java program and a C program. The implementation steps are as follows:
1. Declare the native () method in Java and compile it;
2. Use javah to generate a. h file;
3. Write a. cpp file to implement the native export method, which must contain the. h file generated in step 2 (note that it contains the JNI. h file in JDK );
4. Compile the. cpp file in step 3 into a dynamic link library file;
5. Use the system. loadlibrary () method in Java to load the dynamic link library file generated in Step 4. This Native () method can be accessed in Java.

Java local method
1. To use a feature of the underlying host platform, this feature cannot be accessed through Java APIs.

2. to access an old system or use an existing library, this system or library is not written in Java.

3. to speed up the performance of the program, use sensitive code for a period of time as a local method.

First write the Java File

Package com. hode. hodework. modelupdate;

Public class checkfile
{
Public native void displayhelloworld ();

Static
{
System. loadlibrary ("test ");
}

Public static void main (string [] ARGs ){
New checkfile (). displayhelloworld ();
}
}
Then compiled into a class file based on the written file
Then, execute javah-JNI com. hode. hodework. modelupdate. checkfile in the class root directory such as classes or bin,
A com_hode_hodework_modelupdate_checkfile.h file is obtained in the root directory.
Compile the com_hode_hodework_modelupdate_checkfile.c File Based on the header file.
# I nclude "checkfile. H"
# I nclude
# I nclude

Jniexport void jnicall java_com_hode_hodework_modelupdate_checkfile_displayhelloworld (jnienv * ENV, jobject OBJ)
{
Printf ("Hello world! \ N ");
Return;
}
Compile and generate the DLL file, such as "test. dll". The name is the same as that in system. loadlibrary ("test ").
VC compilation method: CL-I % java_home % \ include \ Win32-LD com_hode_hodework_modelupdate_checkfile.c-fetest. dll
Add the parameter-djava. Library. Path = [DLL storage path] at runtime.

1. What is native method?
To put it simply, a native method is a Java interface that calls non-Java code. A native method is such a Java method: the implementation of this method is implemented by a non-Java language, such as C. This feature is not unique to Java. Many other programming languages use this mechanism, for example, in C ++, you can use extern "c" to notify the C ++ compiler to call a C function.
"A Native method is a Java method whose implementation is provided by non-Java code ."
When defining a native method, it does not provide an implementation body (for example, defining a Java Interface), because the implementation body is implemented outside of the non-Java language ., The following is an example:
Public class ihavenatives
{
Native public void native1 (int x );
Native static public long native2 ();
Native synchronized private float native3 (Object O );
Native void native4 (INT [] ary) throws exception;
}
The declaration of these methods describes how some non-Java code looks like in these Java code (view ).
The identifier native can be used with all other Java identifiers, except abstract. This is reasonable, because native implies that these methods have implementation bodies, but these implementations are non-Java, but abstract clearly specifies that these methods have no implementation bodies. When native is connected with other Java identifiers, its meaning is the same as that of non-native method. For example, native static indicates that this method can be called directly when no class instance is generated, which is very convenient, for example, if you want to use a native method to call a c class library. The third method above uses native synchronized. Before JVM enters the implementation body of this method, it will execute the synchronization lock mechanism (just like Java's multithreading .)
A native method can return any Java type, including non-basic types, and can also perform exception Control. The implementation body of these methods can create an exception and throw it, which is very similar to the Java method. When a native method receives some non-basic types, such as an object or an integer array, this method can access these non-basic types, however, this native method depends on the implementation of the Java class you access. Remember: We can access all Java features in the local implementation of a native method, but this depends on the implementation of the Java features you access, in addition, this is far less convenient and easy to use in Java.
The existence of native method does not affect the calling of these local methods by other classes. In fact, other classes that call these methods do not even know that they call a local method. JVM controls all details of calling local methods. Note that when we declare a local method as final. The method body implemented in Java may improve the efficiency during compilation due to inline. However, it is doubtful whether a native final method can obtain such benefits. However, this is only a problem in code optimization and has no impact on function implementation.
If a class containing a local method is inherited, The subclass will inherit this local method and can be rewritten in Java (this seems strange ), similarly, if a local method is identified by fianl, it cannot be overwritten after being inherited.
The local method is very useful because it effectively expands JVM. in fact, the Java code we have written has used local methods. In the implementation of Sun's Java concurrency (multithreading) mechanism, many contact points with the operating system use local methods, this allows Java programs to go beyond the boundaries of Java runtime. With the local method, Java programs can perform tasks at any application level.

Ii. Why NATIVE METHOD
Java is very convenient to use. However, it is not easy to implement some hierarchical tasks in Java, or we are very concerned about program efficiency.
Interaction outside the Java environment:
Sometimes a Java application needs to interact with an environment outside Java. This is the main reason for the existence of local methods. You can think about the situation that Java needs to exchange information with some underlying systems, such as the operating system or some hardware. The local method is such a communication mechanism: it provides us with a very simple interface, and we do not need to understand the tedious details outside of Java applications.
Interaction with the operating system:
JVM supports the Java language itself and the Runtime Library. It is a platform for survival of Java programs. It consists of an interpreter (interpreted bytecode) and some libraries connected to local code. However, after all, it is not a complete system. It often depends on the support of some underlying (underneath below) systems. These underlying systems are often powerful operating systems. By using the local method, we can use Java to implement the interaction between JRE and the underlying system, and even some parts of the JVM are written in C, if we want to use some java languages that do not provide encapsulated operating system features, we also need to use local methods.
Sun's Java
Sun's interpreter is implemented in C, which enables it to interact with external entities like some common C. Most of the JRE is implemented in Java, and it also interacts with the outside world through some local methods. For example, the setpriority () method of Java. Lang. thread is implemented in Java, but it calls the local method setpriority0 () in the class (). This local method is implemented in C and embedded in JVM. On the Windows 95 platform, this local method will eventually call the Win32 setpriority () API. This is the specific implementation of a local method directly provided by JVM. More often, the local method is provided by external dynamic link library and then called by JVM.

Iii. How does JVM run native method:
We know that when a class is used for the first time, the bytecode of this class will be loaded into the memory and will be loaded only once. At the entry of the loaded bytecode, a list of all the method descriptors of this class is maintained. These method descriptors contain information such as where the method code is stored and what parameters it has, method Descriptor (such as public.
If a method descriptor contains native, this descriptor block will have a pointer to the implementation of this method. These implementations are in some DLL files, but they will be loaded into the address space of the Java program by the operating system. When a class with a local method is loaded, the related DLL is not loaded, so the pointer to the method implementation is not set. These DLL files are loaded only when the local method is called, which is implemented by calling java. system. loadlibrary.

The last thing to note is that using a local method is overhead, and it loses many Java benefits. If you have no choice, you can use the local method.

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.