有这样三个类,Person,Student,GoodStudent。其中Student继承了Person,GoodStudent继承了Student,三个类中只有默认的构造函数,用什么样的方法证明在创建Student类的对象的时候是否调用了Person的构造函数,在创建GoodStudent类的对象的时候是否调用了Student构造函数?如果在创建Student对象的时候没有调用Person的构造函数(我也不知道什么情况下不会去调用,如果都是默认无参构造函数的话),那么采用什么样的手段可以调用父类的构造函数?
一、需要分析
1、Person,Student,GoodStudent三个类的继承关系
2、实现三个class的构造函数
3、打印信息查看各个类的构造函数是否被调用
二、技术点
1、弄清楚Java 类的无参构造函数是默认调用的
2、如果父类的构造函数是有参的,那么要在子类的构造函数的第一行加入super(args); 来确认对哪个父类构造函数的调用
代码:
| 代码如下 | 复制代码 |
packagecom.itheima;
/** * 9、 * 有这样三个类,Person,Student.GoodStudent。其中Student继承了Person,GoodStudent继承了Student, * 三个类中只有默认的构造函数,用什么样的方法证明在创建Student类的对象的时候是否调用了Person的构造函数, * 在创建GoodStudent类的对象的时候是否调用了Student构造函数?如果在创建Student对象的时候没有调用Person的构造函数 * ,那么采用什么样的手段可以调用父类的构造函数? * * @author [email protected] */
publicclassTest9 {
publicstaticvoidmain(String[] args) { Student s1 =newStudent(); System.out.println("-------------------------------"); Student s2 =newStudent(); System.out.println("-------------------------------"); GoodStudent g1 =newGoodStudent(); System.out.println("-------------------------------"); }
}
classPerson {
Person() { System.out.println("I'm Person!"); }
Person(String arg) { System.out.println(arg); }
Person(String arg1, String arg2) { System.out.println(arg1 + arg2); } }
classStudentextendsPerson {
Student() { super("have arg!");// System.out.println("I'm Student!"); }
Student(String arg) { super("have arg!","in Person"); System.out.println(arg); } }
classGoodStudentextendsStudent {
GoodStudent() { super("from GoodStudent!"); System.out.println("I'm GoodStudent!"); }
} | |
打印构造函数的调用过程:
have arg!
I'm Student!
-------------------------------
have arg!
I'm Student!
-------------------------------
have arg!in Person
from GoodStudent!
I'm GoodStudent!
-------------------------------
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环