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 
            +     "\nID: " + 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()初始化會報錯) ,這樣的話,子類繼承該類,就必須要顯示的調用父類的構造函數,這樣才能保證,編譯器在將子類初始化前,父類先被初始化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM