Use of static members in Java __java

Source: Internet
Author: User
Tags rand

(a) Under what circumstances should we use static?
1, just want to use a storage area to save a specific data-no matter how many objects to create, or even do not create objects.
2, we need a special method, it is not associated with any object of this class. That is, even if you do not create an object, you need a

The method that is invoked.

(b) Static means "global" or "static" meaning, used to modify the member variables and member methods, can also form static code

block, but the concept of global variables is not in the Java language.
The member variables and member methods that are decorated by static are independent of any object of the class. That is, it does not depend on class-specific instances, all of the classes

Instance sharing. As long as this class is loaded, the Java virtual machine can find them based on the class name in the method area of the runtime data area. So

A static object can be accessed before any of its objects are created without reference to any object.

(iii) (1) The static members are decorated with public to indicate that they are global members (member variables and member methods) and that when the object of the class is generated, it does not

Generate a copy of the static variable for each object, Java only generates a copy for the static variable, and all the objects of the class share the same copy;

When no class object exists, you access a static member of public with the class name. Member Access.
(2) A static member, decorated with private, can only be accessed through the methods of that class. If there is no object for any class, access to a

Private static member, you must provide a public static method, and you must add the class name and the point operation when calling the method

Specifier is restricted.

(d) Static-modified member variables and member methods are customarily called statically variables and static methods, which can be accessed directly through the class name, and the access language

Method is:
(1) Class name. static method Name (parameter list ...)
(2) class name. Static variable Name
(3) Static {

Whatever code is needed to initialization goes here
}
An expression such as this----a static-decorated block of code that executes the code when the Java Virtual Machine (JVM) loads the class

Block

(v) static variable

There are two types of class member variables that are statically modified: a static variable or a class variable.

The other is a variable that is not modified by static, called an instance variable. The difference between the two is:
For static variables that have only one copy in memory (memory saving), the JVM allocates only one memory for the static, and ends the process of loading the class

Memory allocation as a static variable, which can be accessed directly by the class name (convenient) and, of course, through the object (but this is not recommended).
For an instance variable, no instance is created, and the instance variable is allocated once in memory, and the instance variable can have more than one copy in memory

, and do not affect each other (flexible).

(vi) Static methods
Static methods can be invoked directly through the class name, and any instance can be invoked, so the this and super key cannot be used in static methods

, you cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static), you can only access the owning

Static member variables and member methods for the class. Because instance members are associated with a particular object. This need to understand, to understand the truth, not

Memory.
Because the static method is independent of any instance, the static method must be implemented, not abstract.

(vii) Static code block
A static code block is also known as a code block, which is an independent static statement block in a class that is separate from a class member, and can have multiple locations that can be easily

Put, it is not in any method body, the JVM executes these static code blocks when loading classes, and if there are more than one static code block, the JVM will follow it

They are executed sequentially in the order in which they appear in the class, and each block of code is executed only once. For example:
public class Test5 {
private static int A;
private int B;
static{
Test5.a=3;
System.out.println (a);
Test5 t=new Test5 ();
T.F ();
t.b=1000;
System.out.println (T.B);
}
static{
test5.a=4;
System.out.println (a);
}
public static void Main (string[] args) {
TODO automatically generate method stubs
}
static{
test5.a=5;
System.out.println (a);
}
public void F () {
System.out.println ("Hhahhahah");
}
}
Run Result:
3
Hhahhahah
1000
4
5
This example runs in the order that the Java Virtual machine first calls the Main method (because the Mian method is the entry of the program), and the Main method is located in the Test5 class

, this main method is static, when the Java interpreter finds the path, finds the Test5.class file, and loads the test5.class. At the same time static

State initialization began (including static variables and static code block initialization, static method (except main) can not initialize, can only use the instance

method, static method call, or class name, object invocation.

(eight) Summary of access restrictions for static variables and methods:

(1) Instance methods can access instance variables and instance methods
(2) Instance methods can access static variables and static methods
(3) Static methods can access static variables and static methods
(4) Static methods cannot access instance variables and instance methods. The keyword this and super cannot be used in static methods

(ix) The role of static final modification

In the literal sense, the global constant is represented. The static final modifier variable occupies only a "section" of storage space that cannot be changed

。 That is, the value given to it cannot be changed. If it is a basic type, then the value is immutable; if it is a reference variable, then the reference variable does not

Variable, once the reference is initialized to an object, it cannot be pointed to another object, but the contents of the object can be changed, which is

Say the values of the variables inside this object can be changed. For example: The following marked * * * place

: C06:FinalData.java

Import com.bruceeckel.simpletest.*;
Import java.util.*;

Class Value {
int i; Package Access
Public Value (int i) {this.i = i;}//* * ATTENTION; Here's I is the content of the class can change * * *
}

public class FinalData {
private static Test monitor = new test ();
private static Random Rand = new Random ();
Private String ID;
Public FinalData (String id) {this.id = ID;}
Can Be Compile-time constants:
Private final int val_one = 9;
private static final int val_two = 99;
Typical public constant:
public static final int val_three = 39;
Cannot be Compile-time constants:
Private final int i4 = Rand.nextint (20);
static final int i5 = rand.nextint (20);
Private Value V1 = new value (11);
Private Final Value v2 = new value (22);
Private static final Value v3 = new value (33);
Arrays:
Private Final int[] A = {1, 2, 3, 4, 5, 6};
Public String toString () {
Return ID + ":" + "I4 =" + I4 + ", i5 =" + i5;
}
public static void Main (string[] args) {
FinalData fd1 = new FinalData ("Fd1");
//! Fd1. val_one++; Error:can ' t change value
fd1.v2.i++; Object isn ' t constant!
FD1.V1 = new Value (9); OK--Not final
for (int i = 0; i < fd1.a.length; i++)
fd1.a[i]++; Object isn ' t constant!
//! Fd1.v2 = new Value (0); Error:can ' t
//! Fd1.v3 = new Value (1); Change reference
//! fd1.a = new Int[3];
System.out.println (FD1);
SYSTEM.OUT.PRINTLN ("Creating new FinalData");
FinalData fd2 = new FinalData ("Fd2");
System.out.println (FD1);
System.out.println (FD2);
Monitor.expect (new string[] {
"% Fd1:i4 =//d+, i5 =//d+ ",
"Creating New FinalData",
"% Fd1:i4 =
//d+, i5 =D+ ",
"% Fd2:i4 =
//d+, i5 =//d+ "
});
}
} ///:~

Example (ii)

Package c06.net;

Class value{
static int c=0;
Value () {
c=15;
}
Value (int i) {
C=i;
}
static void Inc () {
C + +;
}
}
Class count{
public static void Prt (String s) {
System.out.println (s);
}
Value V=new value (10);
Static Value V1,v2;
static{
PRT ("v1.c=" +v1.c+ "v2.c=" +v2.c);
V1=new Value (27);
PRT ("v1.c=" +v1.c+ "v2.c=" +v2.c);
V2=new Value (15);
PRT ("v1.c=" +v1.c+ "v2.c=" +v2.c);
}

public static void Main (string[] args) {
Count Ct=new count ();
PRT ("ct.c=" +ct.v.c);
PRT ("v1.c=" +v1.c+ "v2.c=" +v2.c);
V1.inc ();
PRT ("v1.c=" +v1.c+ "v2.c=" +v2.c);
PRT ("ct.c=" +ct.v.c);
}
}

Run Result:

V1.c=0 v2.c=0
V1.c=27 v2.c=27
V1.c=15 v2.c=15
ct.c=10
v1.c=10 v2.c=10
V1.c=11 v2.c=11
ct.c=11

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.