• 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()初始化会报错) ,这样的话,子类继承该类,就必须要显示的调用父类的构造函数,这样才能保证,编译器在将子类初始化前,父类先被初始化。

     
  • 相关阅读:
    在某个点上弹出层
    根据表名、过程名、视图名查找对应的数据库
    js时间转换nan问题 兼容浏览器
    过滤html标记 以及 返回顶部
    自定义控件 加入include 报错 问题
    在有索引视图的表上新增、修改、删除 报错 set ARITHABORT 选项不对
    访微博代码
    兼容问题 链接不跳转
    js上下滚动代码
    onload问题
  • 原文地址:https://www.cnblogs.com/JesseP/p/super_constructor.html
Copyright © 2020-2023  润新知