------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
黑马基础测试题 第九题
package com.itheima;
/**
* 第九题
*
* 有这样三个类,Person,Student,GoodStudent.其中GoodStudent继承于Student,Student继承于Person.
* 如何证明创建GoodStudent时是否调用了Person的构造函数?
* 在GoodStudent中是否能指定调用Student的哪个构造函数?
* 在GoodStudent中是否能指定调用Person的哪个构造函数?
*
* 分析: 创建Person类,Student类继承Person类,GoodStudent类继承Student类,分别创建无参构造函数和有参构造函数.
*
* 1. 证明创建GoodStudent时调用了Person的构造函数
* 在Person类中空参数构造函数里写内容,看是否运行
*
* 2. GoodStudent中指定调用Student的构造函数
* 可以调用,子类构造函数中第一句有默认的super(),把默认改为显示,就可以调用指定的构造函数
*
* 3. GoodStudent中指定调用Person的构造函数
* 不能直接调用,只能通过Student类调用,GoodStudent类和Person类没有直接继承关系
*
*/
public class Test9 {
public static void main(String[] args) {
new GoodStudent();
new GoodStudent("SuperMan", 250);
}
}
//person类
class Person {
// 空参的Person构造函数,被未指定参数的子类构造函数调用
public Person() {
System.out.println("person run");
}
// 带参的Person构造函数,被指定参数的子类构造函数调用
public Person(String name, int age) {
System.out.println("person " + name +"---"+ age);
}
}
// Student_1继承Person
class Student_1 extends Person {
// 空参的Student构造函数,被未指定参数的子类构造函数调用
public Student_1() {
System.out.println("studnt run");
}
// 带参的Student构造函数,被指定参数的子类构造函数调用
public Student_1(String name, int age) {
// super语句,调用带参的Person类构造函数
super(name, age);
System.out.println("student " + name +"---"+ age);
}
}
// GoodStudent继承Student1
class GoodStudent extends Student_1 {
// 默认super();调用空参Student构造函数
public GoodStudent() {
System.out.println("goodstudnt run");
}
public GoodStudent(String name, int age) {
// super语句,调用带参的Student类构造函数
super(name, age);
System.out.println("goodstudent " + name +"---"+ age);
}
}