Java 子类有参构造器报错

Java 子类的有参构造器报错:Implicit super constructor Person() is undefined. Must explicitly invoke another constructor

import java.util.*;

class Person {
    protected String firstName;
    protected String lastName;
    protected int idNumber;
    
    // Constructor
    Person(String firstName, String lastName, int identification){
        this.firstName = firstName;
        this.lastName = lastName;
        this.idNumber = identification;
    }
    
    // Print person data
    public void printPerson(){
         System.out.println(
                "Name: " + lastName + ", " + firstName 
            +     "
ID: " + idNumber); 
    }
     
}

class Student extends Person{
    private int[] testScores;

    /*    
    *   Class Constructor
    *   
    *   @param firstName - A string denoting the Person's first name.
    *   @param lastName - A string denoting the Person's last name.
    *   @param id - An integer denoting the Person's ID number.
    *   @param scores - An array of integers denoting the Person's test scores.
    */
    // Write your constructor here
    Student(String firstName, String lastName, int id,  int[] scores){

     super(); //隐藏会执行的默认构造器
super(firstName, lastName, id); //因为少了父类自定义构造器初始化,所以会报错 this.firstName = firstName; this.lastName = lastName; this.idNumber = id; this.testScores = scores; } /* * Method Name: calculate * @return A character denoting the grade. */ // Write your method here public char calculate(){ int num = testScores.length; int s = 0; for(int score : testScores) { s = s + score; } s = s/num; char grade = '-'; if(s>=90&&s<=100){ grade = 'O'; }else if(s>=80&&s<90){ grade = 'E'; }else if(s>=70&&s<80){ grade = 'A'; }else if(s>=55&&s<70){ grade = 'P'; }else if(s>=40&&s<55){ grade = 'D'; }else if(s<40){ grade = 'T'; } return grade; } } class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String firstName = scan.next(); String lastName = scan.next(); int id = scan.nextInt(); int numScores = scan.nextInt(); int[] testScores = new int[numScores]; for(int i = 0; i < numScores; i++){ testScores[i] = scan.nextInt(); } scan.close(); Student s = new Student(firstName, lastName, id, testScores); s.printPerson(); System.out.println("Grade: " + s.calculate()); } }

原因:父类的构造方法Person()只有有参数的构造方法,也可以说   父类没有无参的构造方法(即默认的super()初始化会报错) ,这样的话,子类继承该类,就必须要显示的调用父类的构造函数,这样才能保证,编译器在将子类初始化前,父类先被初始化。

 
原文地址:https://www.cnblogs.com/JesseP/p/super_constructor.html