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

75 Views Asked by At

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?

2

There are 2 best solutions below

1
Pietii On BEST ANSWER

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

0
Avishek Bhattacharya On

I would suggest to use composition if possible in this case

Instead of using inheritance, you could use composition. Create a separate Employment class and add it as a field in the Person class. This way, you can access employment details when needed, and it can be null for non-employees. Something like

class Employment {
// employment details
}

class Person {
// ...
    private Employment employment;
// ...

}

Alternatively use interface to achieve this as follows

interface Employable {
    String getEmploymentDetails();
}

class Employee extends Person implements Employable {
// ...
    @Override
    public String getEmploymentDetails() {
    // return employment details
    }
}