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

本文通过一个具体的Java程序示例,展示了如何正确实现类的继承,并详细解释了构造函数调用的过程。对比了两种创建子类对象的方法,一种是通过super关键字调用父类构造函数,另一种则是直接在子类构造函数中赋值,后者会导致编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值