Imagine I created two associated classes (Building and Person). A building can accommodate n people (persons) and a person can only be in a building at a time.
The code (just the relevant part of it) so far is:
public class Building {
//some attributes like name, location...
private List<Person> person;
//constructor
//some methods
}
public class Person {
//some attributes like name, age...
private Building building;
//constructor
//some methods
}
Ok, now I need to have more detail on Person so I extend this class to other two (Doctors and Parents), which have their own methods, some of them specifics for each Class.
The code:
public class Parent extends Person {
// some specific attributs
public boolean born;
//constructor
//some methods
public void setChildBorn() {
this.born = true;
}
}
public class Doctor extends Person {
// some specific attributs
// constructor
// some methods
public void maternityWard() {
//HERE THE QUESTION
}
}
So, once arrived here, from maternityWard
method I would need to:
setChildBorn()
.A brief schema would be this:
Building < association > Person
/ extends \
Doctor Parent
And at last, the question: Is it possible to call an exclusive method in a subclass from another subclass? If yes, how would be that code? In case it's possible, I believe that there's some casting here, but I'm not sure how to do this.
Thanks in advance for your help.
You can do this using instanceof
operator and casting
public class Doctor extends Person {
//..some code
public void maternityWard() {
for(Person p : building.getPersonList()){
if(p instanceof Parent){
Parent parent = (Parent)p;
parent.setChildBorn();
}
}
}
P.S. Though this will help you invoking the method of Parent but this is a Bad Practice, though good to understand the language semantics and syntax.
Few good application design practices