如果我们创建一个Immutable类,如下所示,对于Student对象状态的正确性,那么有没有像我们为String那样创建一个新的Object而不调用getInstance方法呢?
public class Student {
private final StringBuffer name;
private final int roll;
private static Student student;
private Student(StringBuffer name , int roll)
{
this.name = name;
this.roll = roll;
}
public static Student getInstance(StringBuffer name,int roll)
{
student = new Student(name, roll);
return student;
}
}
答案 0 :(得分:0)
是的,仍有一种方法可以在不调用类的getInstance方法的情况下创建新实例。这种方式是在Student类的实例上调用clone。因此,如果需要,请覆盖克隆方法并停止。
答案 1 :(得分:0)
不可变对象是指其构造后状态无法更改的对象。因此,您可以将代码更改为类似下面的代码,并且它仍然是不可变的(因为一旦构造了对象,就无法更改对象的状态 - 没有设置者)但同时可以自由构造而没有任何限制:
此外,由于您没有任何getter方法,因此您的代码状态无法访问,因此必须按如下所示添加。
public class Student {
private int roll;
private String name;
private Student(String name , int roll)
{
this.name = name;
this.roll = roll;
}
public String getName() {
return name;
}
public int getRoll() {
return roll;
}
}
您需要实现equals()和hashCode()方法(或使用Eclipse -> Source -> Generated hashCode() and equals()...
方便地生成
答案 2 :(得分:0)
您无法使用“普通”代码直接创建实例,但可以使用反射绕过“private”关键字:
Constructor<Student> c = Student.class.getDeclaredConstructor(StringBuffer.class, int.class);
c.setAccessible(true); // there goes private!
Student s = c.newInstance(new StringBuffer("Bob"), 6);