Java Inheritance & Polymorphism, constructor chaining

mac2024-04-01  28

public class Student{ private String name; private int age; public Student() { System.out.println("Student()"); } public Student(String name, int age) { System.out.println("Student(name, age)"); } } public class UndergraduateStudent extends Student{ public UndergraduateStudent() { System.out.println("UndergraduateStudent()"); } public UndergraduateStudent(String name, int age) { super(name, age); System.out.println("UndergraduateStudent(name, age)"); } public static void printDivisonLine() { System.out.println("----------------------------------------------------------"); } public static void main(String[] args) { Student s1 = new Student(); printDivisonLine(); Student s2 = new Student("kimi", 23); printDivisonLine(); // first invoke the default constructor of the superclass and then invoke the default constructor of the subclass Student s3 = new UndergraduateStudent(); printDivisonLine(); // first invoke the constructor of the superclass and then invoke the corresponding constructor of the subclass Student s4 = new UndergraduateStudent("kimi",23); printDivisonLine(); // first invoke the default constructor of the superclass and then invoke the default constructor of the subclass UndergraduateStudent s5 = new UndergraduateStudent(); printDivisonLine(); // first invoke the constructor of the superclass and then invoke the corresponding constructor of the subclass UndergraduateStudent s6 = new UndergraduateStudent("kimi",23); printDivisonLine(); } } Student() ---------------------------------------------------------- Student(name, age) ---------------------------------------------------------- Student() UndergraduateStudent() ---------------------------------------------------------- Student(name, age) UndergraduateStudent(name, age) ---------------------------------------------------------- Student() UndergraduateStudent() ---------------------------------------------------------- Student(name, age) UndergraduateStudent(name, age) ----------------------------------------------------------
最新回复(0)