Instance analysis of final modifiers in Java
- 2020-04-01 03:33:52
- OfStack
Final modifier:
The final modifier member variable must have the programmer display the specified initial value.
Field of a class: the initial value must be specified in the static initialization block or when the Field is declared.
Instance Field: the initial value must be specified in the declaration Field or constructor in a non-static initial block.
Final local variables: must be initialized by the programmer display.
What is the difference between a final modified base variable and a reference type variable?
Final modifies the base variable: the base variable cannot be reassigned.
Final modifies the reference variable: only ensures that the address referenced by the reference type does not change, i.e
Always reference the same object, but this object can be changed.
/**
*/
import java.util.*;
public class Demo5
{
public static void main(String[] args)
{
final B b = new B(22);
b.test();
//Legal Change the value, but still point to the same reference
b.setAge(20);
System.out.println(b.getAge());
//Illegal < br / >
// b = null;
b.test2();
}
}
/**
fianl Modifier member variable
*/
class A
{
//Legal < br / >
final int a = 10;
//Specifies an initial value
in the constructor or initialization block
final String str;
final int c;
final static double d;
{
str = "hello";
//Illegal < br / >
// a = 100;
}
static
{
d = 100;
}
//The constructor can specify an initial value
for a Field that is not specified in the initialization block
public A()
{
//Illegal < br / >
// str = "ddd";
c = 1000;
}
public double changFinal()
{
//You cannot specify an initial value
for final ina normal method
// return d = 1000.90;
return 0;
}
}
/**
fianl Modify the array object
*/
class B
{
private int age;
public B()
{
}
public B(int age)
{
this.age = age;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
public void test()
{
final int[] arr={23,434,56,898};
System.out.println(Arrays.toString(arr));
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
arr[2] = 200;
System.out.println(Arrays.toString(arr));
// In the face of the Arr To assign a value Illegal < br / >
// arr = null;
}
/**
To deepen the final The understanding of the
*/
public void test2()
{
String str1 = " The bright future ";
//Direct reference to "good future" in the constant pool
String str2 = " happy "+" In the future ";
//true
System.out.println(str1 == str2);
String s1 = " happy ";
String s2 = " In the future ";
String s3 = s1+s2;
//False S1, s2 is just a variable that cannot be determined at compile time
//If you want to confirm at compile time, modify s1, s2
with final
System.out.println(str1 == s3);
}
}
If you are familiar with the final modifier in Java, I believe that it has been explained to you clearly in the comments