Search code examples
javasubclasssuperclass

How to call a subclass method from super's associated class


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 maternityWardmethod I would need to:

  1. Iterate over the Building's Person-ListArray where the Doctor is (that's ok, there's a method for this to get them).
  2. For those objects on the ListArray who are instance of Parent (I can use instanceof Parent, so no point here), call the method 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.


Solution

  • 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

    1. higher and lower label modules should depend on only Abstractions. Depending on concrete class and not on the abstractions injects high coupling. Application should be designed to achieve low coupling and high cohesiveness between classes.
    2. Encapsulation (Building should not expose its state directly for access and modification, but should rather expose methods to handle its state)
    3. instanceof and casting is a code smell, avoid both of them.