final field variable

Tue, Feb 1, 2022 One-minute read

最近看到成员变量用 final 修饰,而一直用 final 修饰常数, 有点好奇,就看了下原因。

public class Game {
    @JsonProperty("id")
    private final String id;

    @JsonProperty("name")
    private final String name;

    @JsonProperty("box_art_url")
    private final String boxArtUrl;
}

这样的写法是没办法用 construcution,

error: cannot assign a value to final variable id this.id = id

所以会很经常和 建造者模式相结合

public class Room {
    private final String bed;// 床 必须
    private final String desk;// 梳妆台 必须
    private final String wardrobe;//衣柜 必须
    private final String cup;// 杯子
    private final String book;// 书

    private Room(Builder builder){
        this.bed = builder.bed;
        this.desk = builder.desk;
        this.wardrobe = builder.wardrobe;
        this.cup = builder.cup;
        this.book = builder.book;
    }
    public static class Builder{
        private String bed;// 床 必须
        private String desk;// 梳妆台 必须
        private String wardrobe;//衣柜 必须
        private String cup;// 杯子 可选
        private String book;// 书 可选

        public Builder(String bed,String desk, String wardrobe){
            this.bed = bed;
            this.desk = desk;
            this.wardrobe = wardrobe;
        }

        public Builder setCup(String cup) {
            this.cup = cup;
            return this;
        }

        public Builder setBook(String book) {
            this.book = book;
            return this;
        }

        public Room build(){
            return new Room(this);
        }
    }
}

final 修饰 String 是为了安全性效率

final 修饰 的 char[] 代表了被储存的资料的不可更改性,但是只是代表引用地址不可变

final int[] array = {1,2,3};

array[2] = 100;

System.out.println(array) ; array: {1, 2, 100}

public static void main(String... args) {
		final List<String> stringList = new ArrayList();
		stringList.add("a");
		stringList.add("b");
		System.out.println(stringList.toString());
	}