Static member Variable
Static variables belong to variables of the class, and instances of all classes share the same variable.
Read and write this variable directly using the class name
Application Scenarios:
Case:
public class Demo04 {
public static void Main (string[] args) {
Static variables belong to variables of class
Read and write this variable directly using the class name
Hoo.z = 10;
int n = hoo.z;
SYSTEM.OUT.PRINTLN (n);//10
instance variable x, y is a variable that belongs to an object
You cannot use an instance variable until you create an object
Each object has its own instance variable
Hoo h1=new Hoo ();//(x, Y)
Hoo h2=new Hoo ();//(x, Y)
Using an instance variable of an object-scoped object
h1.x = 5;
H1.Y = 6;
Test: H1 has its own properties (5,6)
H2 has its own attributes (0,0)
H1,H2 share the same hoo.z
SYSTEM.OUT.PRINTLN (H1);
System.out.println (H2);
Only the same variable that all objects share,
To use static adornments
}
}
Class hoo{
int x, y;
static int z;
Public String toString () {
Return x+ "," +y+ "," +Z;
}
}
Static methods
A
Static method is a method that belongs to a class, and typically uses the class name to call a static method directly.
Static methods differ from Object methods:
• The static method does not have an implied parameter, this (the current object), and the properties and methods of the current object cannot be called.
• The non-static method (the method of the object) passes the object that invokes the method to the this (current object) variable during execution, and can access the properties and methods of the current object.
Usage principle:
If the calculation process of a method uses the data of the current object, you cannot use static methods;
Conversely, if you do not use the current object's data, you can declare it as a static method.
Tip: Most methods of using objects in a program (non-static methods), tool methods and factory methods use static more.
Common tool Methods (static methods):
Math.sqrt (num)
Math.sin ()
Math.Cos ()
arrays.tostring ()
Arrays.sort ()
Arrays.fill ()
static method:
Object method:
Case Code:
public class Demo05 {
public static void Main (string[] args) {
/ *
* static method
*/
//static method is a method belonging to the class, used for the class name
//Call Method: Class name. Method ()
Point p1 = new Point (3, 4);
Point p2 = new Point (6, 8); The
//static method does not have this (current object) during execution!!! The
//static method cannot access the data of the current Object!!
Double D=point.distance (P1, p2);
System.out.println (d);//5.0
//Call a non-static method on an object
//non-static method has this!!!
//can access the data in this (current object)
D = p1.distance (p2);
System.out.println (d);//5.0
//结论:如果一个方法的计算过程使用 //了当前对象的数据,就不能使用静态 //方法,相反如果没有使用当前对象的 // 数据,就可以声明为静态方法。}
}
Class point{
int x, y;
public point (int x, int y) {
This.x=x; This.y=y;
}
/* * Point类中的非静态方法 * 包含隐含参数this,引用调用方法的对象 */public double distance( /* Point this */ Point p2){ //有一个隐含的引用this,引用调用方法 //当前对象,就可以使用这个对象的数据 int a = this.x-p2.x; int b = this.y-p2.y; int c2= a*a+b*b; return Math.sqrt(c2);}/* * 计算过程只用到参数的数据, 所以定义为 * 静态方法。 * 计算两个点p1 和p2 之间的距离(勾股定理) */public static double distance( Point p1, Point p2){ int a = p1.x-p2.x; int b = p1.y-p2.y; int c2 = a*a+b*b; return Math.sqrt(c2);}
}
Static code block
Static code block:
is a class-level code block
Executes during the load of a class and executes only once
Used to process data that is initialized only once, such as: reading picture data, etc.
Case:
public class Demo06 {
public static void Main (string[] args) {
Noo n1 = new Noo ();
Noo n2 = new Noo ();
}
}
Class noo{
/*
* The "code block" can be declared in a class
* Execute code block when creating object
*/
{
System.out.println ("HI");
System.out.println ("code block");
}
/* * 静态代码块 * - 是类级别的代码块 * - 在类的加载期间执行,只执行一次 * - 用于处理只初始化一次的数据,如:读取 * 图片数据。 */static { System.out.println("静态代码块"); System.out.println("静态代码块2");}
}
Final keyword
Final variable
Final modifier variable
Variables that cannot be "re-changed" after initialization.
Final modifier local variable
Can initialize once!! Cannot be "re-changed" after initialization
Case:
int a = 5;
A = 8;//A variable that is not final can modify the value
System.out.println (a);
Final int b = 5;//initialization
b = 8;//compilation error, no more changes
final int C;
c = 5;//can be initialized once!!
c = 8;//compilation error, but cannot change value again!!
System.out.println (c);
Reference variable for final decoration
Can initialize once!! Cannot be "re-changed" after initialization.
Note: It is not possible to change the reference relationship between reference variables and objects, and the members of the object can be arbitrarily changed!
Case:
Final int[] ary = {3,4,5};
ary = null;//compilation error, but cannot change value again!!
ary[0]=5;//can change object contents (array elements)
System.out.println (Ary[0]);//5
Final method parameters
The method parameter is also a local variable, and you can use the final declaration
The parameters of the method are initialized when the method passes the parameter, and cannot be changed within the method after initialization.
Case:
Test (4,5);//call method, initialize parameter variable
public static void Test (
final int A, int b) {
b = 2;
A = 5;//cannot be modified after initialization
System.out.println (A + "," +b);
}
Final properties
The properties of the 1.final decorated object, which cannot be initialized automatically, must be initialized manually.
Can be directly assigned to a value class.
You can also use the constructor to initialize
The 2.final property cannot be changed after initialization.
The 3.final decorated property, which is still an instance variable, or a property that has one for each.
4.final modifier property, when the final variable is the base data type and the string type, if the exact value is known during compilation, the compiler uses it as a compile-time constant. See the article at the end of the code description.
Note: The static modified member variable, which is a variable belonging to the class, is the same variable shared by the whole, unlike the final property.
Case:
Test:
Roo r1 = new Roo (5);
r1.a = 8;//Normal properties can be changed
r1.b = 7;//Compilation error, cannot change final property
Roo r2 = new Roo (6);
Prove that each object has attribute B
System.out.println (r1.b+ "," +r2.b);
Class
Class roo{
int A;
final int b;
public Roo (int b) {
this.b = b;
}
}
Static final declares a constant
Constants that are immutable in the software can be declared as constants
Java replaces constants as constants with "Compile erase" mode
The existing constants are replaced with constants after compilation
This avoids reading constant values to the class during run time, which increases the efficiency of the program's operation.
Case:
public class Demo09 {
public static void Main (string[] args) {
/*
* "Compile erase" technique for testing constants
* Java compiler will be constant during compilation
* K.pi Erase replaced by 3.1415926
* The program does not need to load the K class during operation.
* can also run, and output 3.1415926
*/
System.out.println (K.PI);
K k = new K ();
}
}
Class k{
public static final double pi=3.1415926;
static {
System.out.println ("Load K");
}
}
Final method
The final keyword-decorated method cannot be overridden.
The point of making a method incapable of being overridden is to prevent a child class from being "inadvertently" overridden when defining a new method.
Note: The final decoration method is rarely used in real-world development.
Final class
The final keyword-decorated class cannot be inherited.
Final class Foo {}
Class Goo extends Foo {}
Some of the underlying class libraries in the JDK are defined as final, for example: String, Math, Integer, Double, and so on.
The meaning that a class cannot be inherited is that it can protect the class from being modified, and can control the harm to the system caused by the misuse of inheritance.
Classic topics:
Class MyString extends String () {}
Answer: Compile error, because string is final class cannot be inherited subclass!
Note: The final decorated class is rarely used in real-world development
Test: The final decorated property is "compiled erase" when the class is initialized, and is replaced by a constant.
Package Demo;class Price {//static{//System.out.println ("static Block");// } //class member instance is a price instance StaticPrice INSTANCE =NewPrice (2.8);//1 //Default price Initprice Static DoubleInitprice = -;//2 //Current Price DoubleCurrentprice;//Constructors Public Price(DoubleDiscount) {//super ();System. out. println ("The constructor Initprice was executed:"+ Initprice); Currentprice = Initprice-discount; }} Public classpricetest { Public Static void Main(string[] args) {System. out. println (Price.INSTANCE.currentPrice);//3Price P =NewPrice (2.8);//4System. out. println (P.currentprice);}}
The output results are as follows:
The constructor was executed initprice:0.0
-2.8
The constructor was executed initprice:20.0
17.2
Analysis:
When you first use the price class at tag 3, the program starts initializing the price class and the initialization class is divided into two stages:
The first stage: the system allocates memory space for the variable of price and assigns the default value, i.e. instance = Null,initprice = 0.0,currentprice=0.0;
The second stage: Initializes class variables in the order in which they are initialized, and the program assigns them in turn. The INSTANCE Assignment (new Price (2,8)), D calls the constructor (skips the normal initialization order), passes 2.8 to the discount local variable, and normally the first static price INSTANCE = new Price (2.8); The static double Initprice = 20 is executed again, but because the constructor method is called with new Price (2.8), the normal initialization is skipped, that is, the static double Initprice = 20, and the statement is not executed. That is, the constructor initialization is performed directly with new skipping other initializations, and at this point the initprice is not initialized, which is the default value of 0.0,currentprice=-2.8. The Inintprice is then assigned a value of 20. So when the tag 4 is executed, two static variables are initialized and no longer initialized, at which point the new price (2.8) calls the construction method, Initprice = 20.0, So Currentprice is 17.2.
If you change marker 2 to: final double initprice = 20;//2, the result of the output changes:
The constructor was executed initprice:20.0
17.2
The constructor was executed initprice:20.0
17.2
This is because:
* * When the final variable is the base data type and the string type, if you know its exact value during compilation , the compiler uses it as a compile-time constant.
Because the value of initprice can be determined, the compiler sees it as constant during compilation * *
What is the difference between a class's final variable and a normal variable?
When you use final action on a member variable of a class, the member variable (note is the member variable of the class, the local variable needs to be guaranteed to be initialized before use) must be assigned in the definition or constructor, and once the final variable is initialized, it can no longer be assigned a value.
So what is the difference between a final variable and a normal variable? Let's take a look at the following example:
public class Test {
public static void Main (string[] args) {
String a = "Hello2";
Final String b = "Hello";
String d = "Hello";
String C = b + 2;
String E = d + 2;
System.out.println ((A = = c));
System.out.println ((A = = e));
}
}
We can first think about the output of this problem. Why the first comparison result is true, and the second compares the result to Fasle. This is the difference between the final variable and the normal variable, when the final variable is the base data type and the string type, if you can know its exact value during compilation, the compiler will use it as a compile-time constant. that is, where the final variable is used, it is equivalent to the constant that is accessed directly, and does not need to be determined at run time. This is a bit like a macro substitution in C language. So in the preceding section of code, because the variable B is final decorated, it is treated as a compiler constant, so where B is used, the variable b is replaced directly with its value. The access to variable D needs to be linked at run time. Presumably the difference should be understood, but note that the compiler does this only if the final variable value is known exactly during compilation, as the following code does not optimize:
publicclass Test { publicstaticvoidmain(String[] args) { "hello2"; final String b = getHello(); 2; System.out.println((a == c)); } publicstaticgetHello() { return"hello"; }}
The output of this code is false.
Java Note-static and final detailed notes