黑马程序员技术交流社区

标题: 基础测试中类的继承问题 [打印本页]

作者: 980595778    时间: 2015-5-13 18:12
标题: 基础测试中类的继承问题
基础测试中的一道题
有这样三个类,Person、Student、GoodStudent。 其中GoodStudent继承于Student,Student继承于Person。如何证明创建GoodStudent时是否调用了Person的构造函数?在GoodStudent中是否能指定调用Student的哪个构造函数? 在GoodStudent中是否能指定调用Person的哪个构造函数?
大神们看看这样写对不对?

public class Test9 {
        public static void main(String[] args) {
                GoodStudent goodStudent = new GoodStudent();
        }
}

class Person {
        // 创建一个人类
        Person() {
                System.out.println("Person 无参构造器");
        }

        Person(String arg) {
                System.out.println("Person 有参构造器");
        }

}

// 创建一个学生类;继承于人类
class Student extends Person {
        Student() {
                super("继承 Person"); //
                System.out.println("Student 无参构造器");
        }

        Student1(String arg) {
                super("继承 Person");
                System.out.println("Student 有参构造器");
        }
}

// 创建一个goodstudent类继承于学生类;
class GoodStudent extends Student {
        GoodStudent() {
                super("继承 Student");
                System.out.println("我是 GoodStudent");
        }

}



作者: yky1678    时间: 2015-5-13 18:39
你这都显示的写出了调用父类的构造函数了,怎么还能证明呢。
你直接把super去掉,实例化的子类对象的时候,父类的无参构造函数会默认被调用,你的输出结果会有你的无参构造函数里的语句
作者: shentan000    时间: 2015-5-13 21:20
看看~看看~~
作者: lostaloneesk    时间: 2015-5-13 21:24
把super去掉,然后来看打印经过,你这个就能知道了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2