java immutable class example

Where the final keyword can be used
Modifier class: this class cannot be inherited
Modifier variable: once initialized, the variable cannot be reassigned, even if the value is the same as the initialized value or points to the same object
Class variables:
Instance variable:
Formal parameters: note that formal parameters can be modified
local variable
Decorated method: this method cannot be overridden
final decorated member variable
The final decorated member variable must explicitly specify the initial value. The system will not implicitly initialize the final member and cannot access it before initialization.
Because, whether it is a class variable or an instance variable, there is an initialization process. After the initialization assignment, the assignment can no longer be performed. If the initial value is not explicitly specified, then these variables have no significance
Modifier class variable:
Either specify when declaring
Either specify in static block
They are mutually exclusive, only one of them
Decorated instance variable:
Either specify when declaring
Either specified in a non static block
Either specified in the constructor
Any two of them are mutually exclusive, which can only be one of them
final modifying local variables
Local variables, with or without final modifiers, must be explicitly initialized
The parameter modified by final cannot be assigned
final modifier reference type variable
final can be used to modify a reference type variable, but only to ensure that the variable always points to the same address
There is no guarantee that the target itself will change
final and direct quantity
A variable, whether it is a class variable, an instance variable or a local variable, is a direct quantity if it satisfies the following three conditions
Decorate with final
The initial value was specified when the final variable was defined. Note that when it is defined, it cannot be in code block or construction method
This initial value can be determined at compile time
For direct variables, the variable name will be replaced with direct variables during compilation. This variable does not exist in the compiled file
Java uses constant pool to manage used string direct quantity
final decoration method
The method decorated with final cannot be overridden. For example, the Object as the root parent class has a. getClass() method decorated with final
If the parent class has a method modified by private final and the child class has the same method, private final and the method signature are the same. Note that this is not an override. These are two unrelated methods,
final modifier class
The final decorated class cannot be inherited, for example:
public final class Math extends Object {...}
Immutable class
Immutable class: after an instance is created, the instance variable is immutable, that is, the state of the instance cannot be changed
Eight wrapper classes and String are immutable
How to define an immutable class:
Modifying member variables with private and final
Provides a constructor with parameters to initialize member variables
Only get method of member variable is provided, not set method
Override the equals() and hashCode() methods if necessary
If the member variable is a reference type
In this case, it should be noted that the above method can only be used for basic types
For the immutable writing method of reference type, the basic principle is to isolate external access to it. There are two main points to be done:
The reference type object passed in should not be used directly, but recreated according to its instance variable
During external access, according to the value of the instance variable of this object, recreate an object to return
See the following example code:
Example 1:

public class Test{  
    public static void main(String[] args) { 
        Name n=new Name("Elder brother","large");
        System.out.println(n);            //Name@15db9742
        Person p=new Person(n,100);
        System.out.println(p);            //Output: [elder martial brother, 100 years old]
        System.out.println(p.getName());  //Name@15db9742
        n.setFirstName("Elder brother");
        n.setLastName("Two");
        System.out.println(p);            //Output: [elder martial brother 2 is 100 years old], immutable object has changed. Look at the following code again
        System.out.println(p.getName());  //Name@15db9742
    }
}
class Person{
    private final Name name;
    private final int age;
    public Person(Name name,int age){
        this.name=name;
        this.age=age;
    }
    public Name getName(){
        return name;
    }
    public String toString(){
        return "["+name.getLastName()+name.getFirstName()+age+"year]";
    }
}
class Name{
    private String firstName;
    private String lastName;
    public Name(){}
    public Name(String first,String last){
        firstName=first;
        lastName=last;
    }
    public String getFirstName(){
        return firstName;
    }
    public void setFirstName(String firstName){
        this.firstName=firstName;
    }
    public String getLastName(){
        return lastName;
    }
    public void setLastName(String lastName){
        this.lastName=lastName;
    }
}

Example 2 rewrites two lines:

public class Test{  
    public static void main(String[] args) { 
        Name n=new Name("Elder brother","large");
        System.out.println(n);            //Name@15db9742
        Person p=new Person(n,100);
        System.out.println(p);            //Output: [elder martial brother, 100 years old]
        System.out.println(p.getName());  //Name@6d06d69c
        n.setFirstName("Elder brother");
        n.setLastName("Two");
        System.out.println(p);            //Output: [senior brother is 100 years old]. No change
        System.out.println(p.getName());  //Name@7852e922
    }
}
class Person{
    private final Name name;
    private final int age;
    public Person(Name name,int age){
        this.name=new Name(name.getFirstName(),name.getLastName());  //Rewrite this line
        this.age=age;
    }
    public Name getName(){
        return new Name(name.getFirstName(),name.getLastName());     //Rewrite this line
    }
    public String toString(){
        return "["+name.getLastName()+name.getFirstName()+age+"year]";
    }
}
class Name{
    private String firstName;
    private String lastName;
    public Name(){}
    public Name(String first,String last){
        firstName=first;
        lastName=last;
    }
    public String getFirstName(){
        return firstName;
    }
    public void setFirstName(String firstName){
        this.firstName=firstName;
    }
    public String getLastName(){
        return lastName;
    }
    public void setLastName(String lastName){
        this.lastName=lastName;
    }
}
Published 4 original articles, won praise 2, visited 14
Private letter follow

Tags: Java

Posted on Mon, 13 Jan 2020 21:42:22 -0800 by jfarthing