关于final修饰的成员变量
由书本上讲的,final修饰的成员变量一经赋值便不会改变,于是我创建了个类Address,其实例final修饰的 Field为detail,postCode.用两个构造方法对其初始化,按理说其Field经过其中一个构造方法初始化后其值便不再改变,即Address类的所有对象为同一个对象,所以当用重写的equals方法比较时应返回true,但是测试结果
为false.希望懂的朋友指点迷津。下面是我的代码:
class Address
{
private final String detail;
private final String postCode;
public Address()
{
this.detail = "";
this.postCode = "";
}
public Address (String detail, String postCode)
{
this.detail = detail;
this.postCode = postCode;
}
public String getDetail()
{
return this.detail;
}
public String getPostCode()
{
return this.postCode;
}
public boolean equals(Object obj)
{
//Object obj = obj;
if(this == obj)
{
return true;
}
if (obj != null && obj.getClass() == Address.class)
{
Address ad = (Address)obj;
if (this.getDetail().equals(ad.getDetail()) && this.getPostCode().equals(ad.getPostCode()))
{
return true;
}
}
return false;
}
public int hashCode()
{
return detail.hashCode() + postCode.hashCode() * 31;
}
public void print()
{
System.out.println(this.hashCode());
System.out.println(this.detail);
System.out.println(this.postCode);
}
}
public class Test
{
public static void main(String[] args)
{
Address pr1 = new Address();
Address pr2 = new Address("水月" , "镜花");
Address pr3 = new Address("loving" , "java");
pr1.print();
pr2.print();
pr3.print();
//输出false
System.out.println(pr1.equals(pr2));
//输出false
System.out.println(pr2.equals(pr3));
}
}