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, but you always have the risk of getting a ClassCastException
if there was a Doctor
object in the person
list, and you forgot to use instanceof
. If not, lets say you store the Person
in a variable called p
. Then, to access the method do:
((Parent) p).setChildBorn();
Is it possible to call an exclusive method in a subclass from another subclass?
An exclusive method's visibility in other subclasses (ie sibling classes) is the same as that in a non-sibling class and it follows the same access control as applicable for any non-sibling class.
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();
}
}
}
PS 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.