您的位置:首页 > 编程语言 > Java开发

Java继承,在构造函数内对父类初始化的问题

2016-09-16 23:29 351 查看
source: https://www.hackerrank.com/challenges/30-inheritance?h_r=next-challenge&h_v=zen
Student的创造方法,这样子写:

    Student(String firstName, String lastName, int id, int[] testScores) {

        super(firstName, lastName, id);

        this.testScores = testScores;

    }

是可以的,

但,若这样子写:

    Student(String firstName, String lastName, int id, int[] testScores) {

        this.firstName = firstName;

        this.lastName = lastName;

        this.idNumber = id;

        this.testScores = testScores;

    }

就会报错:如下:

Solution.java:26: error: constructor Person in class Person cannot be applied to given types;
Student(String firstName, String lastName, int id, int[] testScores) {
^
required: String,String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error


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;

    

    Student(String firstName, String lastName, int id, int[] testScores) {

        super(firstName, lastName, id);

        this.testScores = testScores;

    }

    

    public char calculate(){

        int avg = Arrays.stream(testScores).sum()/testScores.length;

        if (avg >= 90) return 'O';

        if (avg >= 80) return 'E';

        if (avg >= 70) return 'A';

        if (avg >= 55) return 'P';

        if (avg >= 40) return 'D';

        return 'T';

    }

}

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() );

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 构造函数