final 类和不可变类

原文链接:http://quanquan127.iteye.com/blog/1558401

https://blog.csdn.net/topwqp/article/details/46433283

1.final 类 

final修饰的类不可有子类,例如java.lang.Math类就是一个final类,它不可以有子类。 

为了保证某个类不可以被继承,则可以使用final修饰这个类。下面的代码示范了final修饰的类不可以被继承。 

public final class FinalClass { } 
//下面类定义将出现编译错误 
class Sub extends FinalClass { } 

因为FinalClass类是一个final类,而Sub试图继承FinalClass类,这将会引起编译错误。 


2.不可变类 

不可变类的意思是创建该类的实例后,该实例的属性是不可以改变的。Java提供的8个包装类和java.lang.String都是不可变类,当创建它们的实例后,其实例的属性不可变。例如下面代码: 

Double d=new Double(6.5); 
String str=new String("hello"); 

上面程序创建了一个Double对象和一个String对象,并为这两个对象传入了6.5和"hello"字符串作为参数,那么Double类和String类肯定需要提供实例属性来保存这两个参数,但程序无法修改这两个实例属性,因此Double类和String类没有提供修改它们的方法。 

如果需要创建自定义的不可变类,可遵守如下规则: 
(1)使用private final 修饰符来修饰该类的属性 
(2)提供带参数构造器,用于根据传入参数来初始化类里的属性。 

(3)仅为该类的属性提供getter方法,不要为该类提供setter方法,因为普通方法无法修改final修饰的属性 

(4)如果有必要,重写Object类中的hashCode和equals方法。在equals方法根据关键属性来作为两个对象相等的标准,除此之外,还应该保证两个用equals方法判断为相等的对象的hashCode也相等。






不可变类:一旦创建,状态无法改变 
关于创建不可变类有很多规则,下面一一介绍这些规则: 
目录

  1. 定义不可变类的益处
  2. 定义不可变类指南

定义不可变的益处

  1. 构造简单,便于测试和使用
  2. 不可变类自然是线程安全的,无需关心多线程和同步问题
  3. 不需要实现clone
  4. 可以延迟加载,缓存它的返回值
  5. 由于不可变可以用于Map的key和Set的元素(set元素不能重复)
  6. 当作为属性时,不需要深度clone

如何让类不可变

在Java文档中,有关于如何定义不可变类指南: click here

  1. 不提供setter方法,setter方法用于修改属性和对象引用 
    这个原则阐述了在你类定义的所有可变属性中,不提供setter方法,setter方法意味着你能够改变这个属性的状态。必须阻止提供setter方法
  2. 所有的属性修饰添加private和final 
    这是另外一种增加不可变的方式,属性声明为private为了在类之外不能够被访问到,final修饰符为了让你不能随便的改变它们
  3. 不允许子类重写方法 
    最简单的方式声明类为final,final类不允许被重写
  4. 当属性中存在可变对象变量时,要特别留意 
    永远铭记你的对象变量,不是可变的就是不可变的(这句好像是废话。。),识别出来可变对象,对可变对象的内容进行copy,并创建一个新对象赋值给它,这样保证可变对象的不可变,通过直接copy对象内容的形式,保持数据不可变
  5. 来点优雅的,定义一个private的构造方法,通过 工厂方法构造对象

    只说太抽象,还是来点实例痛快


import java.util.Date;

/**
* Always remember that your instance variables will be either mutable or immutable.
* Identify them and return new objects with copied content for all mutable objects.
* Immutable variables can be returned safely without extra effort.
* */
public final class ImmutableClass
{

    /**
    * Integer class is immutable as it does not provide any setter to change its content
    * */
    private final Integer immutableField1;
    /**
    * String class is immutable as it also does not provide setter to change its content
    * */
    private final String immutableField2;
    /**
    * Date class is mutable as it provide setters to change various date/time parts
    * */
    private final Date mutableField;

    //Default private constructor will ensure no unplanned construction of class
    private ImmutableClass(Integer fld1, String fld2, Date date)
    {
        this.immutableField1 = fld1;
        this.immutableField2 = fld2;
        this.mutableField = new Date(date.getTime());
    }

    //Factory method to store object creation logic in single place
    public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
    {
        return new ImmutableClass(fld1, fld2, date);
    }

    //Provide no setter methods

    /**
    * Integer class is immutable so we can return the instance variable as it is
    * */
    public Integer getImmutableField1() {
        return immutableField1;
    }

    /**
    * String class is also immutable so we can return the instance variable as it is
    * */
    public String getImmutableField2() {
        return immutableField2;
    }

    /**
    * Date class is mutable so we need a little care here.
    * We should not return the reference of original instance variable.
    * Instead a new Date object, with content copied to it, should be returned.
    * */
    public Date getMutableField() {
        return new Date(mutableField.getTime());
    }

    @Override
    public String toString() {
        return immutableField1 +" - "+ immutableField2 +" - "+ mutableField;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

验证以上不可变类:


import java.util.Date;

public class MainTest
{
    public static void main(String[] args)
    {
        ImmutableClass im = ImmutableClass.createNewInstance(100,"test", new Date());
        System.out.println(im);
        tryModification(im.getImmutableField1(),im.getImmutableField2(),im.getMutableField());
        System.out.println(im);
    }

    private static void tryModification(Integer immutableField1, String immutableField2, Date mutableField)
    {
        immutableField1 = 10000;
        immutableField2 = "test changed";
        mutableField.setDate(10);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

输出结果如下: 
100 - test - Tue Jun 09 23:14:01 CST 2015 
100 - test - Tue Jun 09 23:14:01 CST 2015

从输出中可以看出:即使通过对象引用改变对象变量,值依然不改变,因此类是不可变类


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值