Overload constructor in inherited class

1

I have a Person class that has the following constructor

Person(String firstName, String lastName, int identification){

And a student class that extends from Person and whose constructor I want to add one more parameter, which are the notes. To do this, I extend and create a new constructor

class Student extends Person{
private int[] testScores;

Student(String firstName, String lastName, int identification, int[] numScores){

The problem is that the compiler gives me an error here, because:

constructor Person in class Person can not be applied to given types, requiered String, String, int.

Let's see that it does not overload the constructor of the Persona class and it still tells me that the Persona constructor only has 3 arguments.

How can I solve this error? It's for an exercise and I can not create a new constructor in the Person class with the 4 arguments, but it has to be a constructor in the student class.

Thank you.

    
asked by pitiklan 25.11.2016 в 09:47
source

4 answers

1

Surcharge it like this:

Student(String firstName, String lastName, int identification, int[] numScores){
    super(firstName, lastName, identification);
    this.testScores = numScores;
}
    
answered by 25.11.2016 в 09:56
1
class Student extends Person{
private int[] testScores;

public Student(String firstName, String lastName, int identification, int[]numScores){
  super(firstName, lastName, identification);
  this.testScores= numScores;
}

With super() , you call the constructor of the father and with this.testScores= numScores; you add the new attribute of the Student class

    
answered by 25.11.2016 в 09:57
0

I think I found the answer.

The problem is that I did not have a default constructor defined. I have created the constructor Persona () {} and the error in the class student has disappeared.

    
answered by 25.11.2016 в 09:55
0

Builders DO NOT INHERIT . That is why you can overload only between constructors of the same class (for example, between two Student(...) ).

However, the first thing that each constructor does is call the constructor of the parent class 1 . It can be done explicitly with super([parámetros]) , but if you do not do it the constructor does it implicitly calling the constructor by default.

The problem here is that there is no default constructor in the parent class, so you'll have to make the call explicit (remember, it should be the first instruction).

Student(
  String firstName,
  String lastName,
  int identification,
  int[] numScores){

  super(
    firstName,
    lastName,
    identification);
  ...

1 And the first thing that the constructor of the parent class will do is call a constructor of its parent class, thus reaching Object .     
answered by 25.11.2016 в 09:56