JAVA 接口与继承作业——动手动脑以及课后实验性问题

一、继承条件下的构造方法调用

运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大!

1)  源代码

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();

    }

}

2)运行结果截图

3)结论

通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

一、参看ExplorationJDKSource.java示例

1)  源代码

public class ExplorationJDKSource {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

        System.out.println(new A());

    }

 

}

class A{}

2)  运行结果截图

 

3)结论

前面示例中,main方法实际上调用的是:

public void println(Object x),这一方法内部调用了String类的valueOf方法。

valueOf方法内部又调用Object.toString方法:

public String toString() {

         return getClass().getName() +"@" +

         Integer.toHexString(hashCode());

}

hashCode方法是本地方法,由JVM设计者实现:

public  native int hashCode();

原文地址:https://www.cnblogs.com/justmaomao/p/4948050.html