简体   繁体   中英

Design Pattern: OOPs and Inheritance

I have one Parent class and two Child Classes. Also it has getEmployeeDetails which returns Type Employee. Employee is an abstract class extended by Manager and Engineer.

Sample Code:

public class Parent{

    public Employee getEmployeeDetails(int id){
        //doStuff
    }
}

public class child1 extends Parent{
    @Override
    public Manager getEmployeeDetails(int id){
        //doStuff
    }
}

public class child2 extends Parent{
}

Now I want my child1 to override getEmployeeDetails and return type manager. Also if I want to set employee specific details in Parent and override this and add on more to oveerridden method, what should be done in parent as Employee is abstract class? Also, please suggest any better pattern.

public abstract class Parent{

    public final Employee getEmployeeDetails(int id){
        //doStuff
        return getEmployeeDetailsImpl(id);
    }

    protected abstract Employee getEmployeeDetailsImpl(int id);
}

public final class child1 extends Parent{
    @Override
    protected final Employee getEmployeeDetails(int id){
        //doStuff
        return new Manager(id);
    }
}

public final class child2 extends Parent{
    @Override
    protected final Employee getEmployeeDetails(int id){
        //doStuff
        return new Engineer(id);
    }
}

You may need to adapt the signature of getEmployeeDetailsImpl according to your needs.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM