一、包装类(wrapper)
所有的包装类都有 final 修饰的。
public final class Paper {
}
当定义但没有赋值的变量直接打印会报 Variable 'a' might not have been initialized
的错误,是因为未赋值的变量不能直接打印,但其是由默认值的。
1.不变类
final 修饰的某个类,且该类中的所有实例变量都是不可更改的。
- 所有变量是 final 修饰的
- 若类中的变量不是通过 final进行修饰的实例变量,则对其不提供修改的方法,但是这回种方法并 不可靠(所以不提倡)。
判断是否为不变类的两个条件:
- 被 final 修饰的类(最终变量)
- 不可更改的实例变量。
package com.kaifamiao.wrapper;
public final class Paper {
private final String color;
private final String size;
private final int count;
public Paper(String color, String size, int count) {
this.color = color;
this.size = size;
this.count = count;
}
@Override
public String toString() {
return "这个纸张是" + color +"的,大小为" + size + ",有" + count + "张。";
}
public static void main(String[] args) {
Paper p = new Paper("白色" , "A4" , 1);
System.out.println(p);
Paper a = new