Search code examples
javainheritanceclasscastexceptionreusability

Is it bad to use an instance of an operator to access child class variables from a parent reference?


I have a class, e.g., Person, having some parameters, e.g., name and age. Now I want to add some other parameters, e.g., employment. These new parameters are only useful to one mode of the applications.

So I was creating a subclass, Employee, extends Person. And reuse all the common code by passing around a Person reference.

Person p = new Employee();

But I want to access employee-specific parameters. How can I achieve that?

I thought of adding instanceOf and casting to Employee, but it leads to many if else conditions. What else can I do? How can I restructure to reuse existing code, but still use new parameters in just one mode of the application?


Solution

  • It sounds like you want to add specific parameters (employment in this case) to the Person class for a specific mode of your application, but you also want to reuse common code between Person and Employee. One way to achieve this is by using composition and interfaces rather than inheritance.

    Create an interface or an abstract class for the common properties and methods shared between Person and Employee. e.g. Human

    Create a concrete class Person that implements the Human interface and includes properties and methods common to all instances of Human

    Create a separate class Employee that also implements the Human interface and includes the additional properties specific to employees

    Now, in your application, you can create instances of both Person and Employee and access their specific properties while still treating them as Human objects