黑马程序员----基础题----我的基础题

本文通过实例详细解析了Java中不同类之间的继承关系,并展示了如何验证子类构造时父类构造函数的调用过程,以及如何指定调用特定构造函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值