如何创建不可变类

时间:2012-04-12 17:51:22

标签: java

我想让下面的类成为不可变的。任何人都可以提供一个在java中创建不可变类的简单示例吗?

class Emp implements Comparable
{
      String name,job;
      int salary;
      public Emp(String n,String j,int sal)
      {
         name=n;
         job=j;
         salary=sal;
       }
      public void display()
      {
        System.out.println(name+"\t"+job+"\t"+salary);
       }
     public boolean equals(Object o)
      {

        // use a shortcut comparison for slightly better performance; not really required  
            if (this == o)  
            {  
                return true;   
            }  
            // make sure o can be cast to this class  
            if (o == null || o.getClass() != getClass())  
            {  
                // cannot cast  
                return false;  
            }            
            // can now safely cast       
          Emp p=(Emp)o;
          return this.name.equals(p.name)&&this.job.equals(p.job) &&this.salary==p.salary;
       }
      public int hashCode()
       {
          return name.hashCode()+job.hashCode()+salary;
       }


       public int compareTo(Object o)
       {
          Emp e=(Emp)o;
          return this.name.compareTo(e.name);
           //return this.job.compareTo(e.job);
        //   return this.salary-e.salary;

        }
} 

2 个答案:

答案 0 :(得分:3)

只需将您班级的所有字段标记为final,并且除了您班级的构造函数外,不要将它们分配给它们。

答案 1 :(得分:2)

此外,最好使类最终,或仅提供私有构造函数和静态工厂方法。这意味着人们不能将您的类子类化并覆盖您的方法。

例如:

public class Immutable {
    private final String value;
    private Immutable(String value) {
        this.value = value;
    }
    public static Immutable create(String value) { return new Immutable(value); }
    public String getValue() { return value; }
}