欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2022-05-21 10:48:57|栏目:JAVA代码|点击:

有这样三个类,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!
-------------------------------

上一篇:如何在不使用spring框架中使用aop的功能

栏    目:JAVA代码

下一篇:Java中超详细this与super的概念和用法

本文标题:java Person,Student,GoodStudent 三个类的继承、构造函数的执行

本文地址:http://www.codeinn.net/misctech/202439.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有