代码一:
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 调用基类构造方法,必须是子类构造方法中的第一个语句。
代码二:
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();
}
}
运行结果:
代码三:
public class ExplorationJDKSource {
/** * @param args */ public static void main(String[] args)
{
System.out.println(new A());
}
}
class A{}
运行结果:
代码四:
public class Fruit {
public String toString()
{
return "Fruit toString.";
}
public static void main(String args[])
{
Fruit f=new Fruit();
System.out.println("f="+f);
// System.out.println("f="+f.toString());
}
}
结果截图:
代码五:
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();
}
}