-3

我想让下面的类不可变。谁能提供一个在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;

        }
} 
4

2 回答 2

3

只需将类的所有字段标记为final,并且不要将它们分配给除类的构造函数之外的任何地方。

于 2012-04-12T17:54:13.753 回答
2

此外,最好将类设为 final,或者只提供私有构造函数和静态工厂方法。这意味着人们不能继承你的类并覆盖你的方法。

例如:

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; }
}
于 2012-04-12T17:56:03.957 回答