java Person Student GoodStudent three classes of inheritance constructor execution

  • 2020-06-12 09:03:36
  • OfStack

There are three classes, Person,Student,GoodStudent. Student inherits Person,GoodStudent inherits Student, and there is only default constructor in the three classes. What kind of method can be used to prove whether the constructor of Person is called when creating the object of Student class and whether the constructor of Student is called when creating the object of GoodStudent class? If the Student object is created without calling the Person constructor (and I don't know when not, if it's the default no-argument constructor), what kind of way to call the superclass constructor?

1. Need analysis

1, Person,Student,GoodStudent3 class inheritance relationship
2. Implement three class constructors
3. Print the information to see if the constructor of each class is called

2. The technical points

1. Make sure that the Java class's no-argument constructor is called by default
2. Add super(args) to the first line of the constructor of the subclass if the constructor of the parent class is parameterized; To confirm which parent constructor to call

Code:


package com.itheima;

/**
 * 9 , 
 *  There are such 3 A class, Person,Student.GoodStudent . Among them Student inherited Person,GoodStudent inherited Student,
 * 3 There are only default constructors in the class. What method is used to prove the creation Student Object of the class Person The constructor of, 
 *  When creating a GoodStudent Object of the class Student Constructor? If you are creating Student Object is not called Person Constructor of 
 *  In what way can the constructor of the parent class be called? 
 * 
 * @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!");
	}

}

The call procedure of the print constructor:


have arg!
I'm Student!
-------------------------------
have arg!
I'm Student!
-------------------------------
have arg!in Person
from GoodStudent!
I'm GoodStudent!
-------------------------------


Related articles: