Reputation: 742
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.
Upvotes: 4
Views: 320
Reputation: 7325
Change the patient constructor to this.
public Patient(String hospNumber) {
super(lookup(hospNumber,"firstname"), lookup(hospNumber,"surname"));
}
But the lookup
method needs to be static in order to do this.
Otherwise you will have to change it to:
public Patient(String hospNumber, String firstname, String surname) {
super(firstname,surname);
}
Or something similar.
Finally you could also add another constructor to the Person class. like Person()
and set the rest of the details later. this way you don't have to even write super() on the constructor of the patient.
Side notes: A class can have more than 1 constructors as long as they do not have the same parameters.
super()
calls the constructor of the super-class (that class from which this class inherits).
Upvotes: 2
Reputation: 3456
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"));
}
Upvotes: 2
Reputation: 43456
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.
Upvotes: 5