当前位置: 移动技术网 > IT编程>开发语言>Java > java Person,Student,GoodStudent 三个类的继承、构造函数的执行

java Person,Student,GoodStudent 三个类的继承、构造函数的执行

2019年07月22日  | 移动技术网IT编程  | 我要评论

有这样三个类,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); 来确认对哪个父类构造函数的调用

代码:

package com.itheima;

/**
 * 9、
 * 有这样三个类,person,student.goodstudent。其中student继承了person,goodstudent继承了student,
 * 三个类中只有默认的构造函数,用什么样的方法证明在创建student类的对象的时候是否调用了person的构造函数,
 * 在创建goodstudent类的对象的时候是否调用了student构造函数?如果在创建student对象的时候没有调用person的构造函数
 * ,那么采用什么样的手段可以调用父类的构造函数?
 * 
 * @author 281167413@qq.com
 */

public class test9 {

	public static void main(string[] args) {
		student s1 = new student();
		system.out.println("-------------------------------");
		student s2 = new student();
		system.out.println("-------------------------------");
		goodstudent g1 = new goodstudent();
		system.out.println("-------------------------------");
	}

}

class person {

	person() {
		system.out.println("i'm person!");
	}

	person(string arg) {
		system.out.println(arg);
	}

	person(string arg1, string arg2) {
		system.out.println(arg1 + arg2);
	}
}

class student extends person {

	student() {
		super("have arg!"); //
		system.out.println("i'm student!");
	}

	student(string arg) {
		super("have arg!", "in person");
		system.out.println(arg);
	}
}

class goodstudent extends student {

	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!
-------------------------------

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网