Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a class with a different constructor?

I am having difficulty extending a person class to a patient class

I have a Person class with a constructor looking like

  public Person(String firstname,String surname) {
        fFirstname=firstname;
        fSurname=surname;
    }

I then have a Patient Class

public class Patient extends Person

I want to have a constructor for a patient looking roughly like

public Patient(String hospNumber) {
    fFirstname = lookup(hospNumber,"firstname");
    fSurname = lookup(hospNumber,"surname");
}

However I get a complaint that the Patient constructor needs (String,String). I can see why this is, but can't see how to extend the person class for a patient.

like image 819
Tony Wolff Avatar asked Jan 05 '23 16:01

Tony Wolff


2 Answers

Just pass the result of those two method calls to the super constructor:

public Patient(String hospNumber) {
    super(lookup(hospNumber,"firstname"), lookup(hospNumber,"surname"));
}

Those methods have to be static, since the this they would otherwise been called on hasn't been constructed yet when they're invoked.

like image 194
yshavit Avatar answered Jan 15 '23 07:01

yshavit


Either you can have a default constructor in Person class

public Person() {

}

Or

You need to call constructor the Person class using super method as its a 2-arg constructor

public Patient(String hospNumber) {
    super(lookup(hospNumber,"firstname"), lookup(hospNumber,"firstname"));
}
like image 34
Arjit Avatar answered Jan 15 '23 06:01

Arjit