一:关于构造函数的继承
class Grandparent { public Grandparent() { System.out.println("GrandParent Created."); } public Grandparent(String string) { System.out.println("GrandParent Created.String:" + string); } } class Parent extends Grandparent { public Parent() { super("Hello.Grandparent."); System.out.println("Parent Created"); //super("Hello.Grandparent."); } } class Child extends Parent { public Child() { System.out.println("Child Created"); } } public class TestInherits { public static void main(String args[]) { Child c = new Child(); } }
从上面的例子可以看出子类在调用构造函数时,会先调用父类的构造函数,在调用父类的函数时,如果父类的构造函数有参数,如果要调用父类的有参数的构造函数,必须加上super(参数),而且必须将super语句放在第一句。
二:不可变类
public final 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; } //仅为两个实例属性提供getter方法 public String getDetail() { return this.detail; } public String getPostCode() { return this.postCode; } //重写equals方法,判断两个对象是否相等。 public boolean equals(Object obj) { if (obj instanceof Address) { 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(); } }
不可变的类即为不能继承的类,此类用于方便和安全的进行多线程的操作。