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

     
  • 相关阅读:
    谈谈我的经历--【产品设计中遇到的坑0】系列文章的序
    2017.02.04,读书,2017第二本《把时间当作朋友》读书笔记
    读书《重生,七年就是一辈子》
    好剧推荐:This is us
    直播预告:产品设计中不得不知的事情
    高德地图事件与插件绑定
    高德地图基础
    es6 Iterator和for...of循环
    class与class的继承
    JS保留两位小数的几种方法
  • 原文地址:https://www.cnblogs.com/JesseP/p/super_constructor.html
Copyright © 2011-2022 走看看