1

This is a question asked to me in an interview. I have one class say EmployeeClass with two method. EmployeeDetails, SalaryDetails. Now I have two More Class Employee and Hr. My need is when I create employee object only EmployeeDetails() method should be accessible and when when i create HR class both EmployeeDetails() and SalaryDetails() should be accessiable. I need to define a prototpe using all solid principle.

Class EmployeeClass 
{
    EmployeeDetails();
    SalaryDetails();
}

and:

Class Employee
{
}
Class Hr
{
}

and:

void Main()
{
    var employee = new Employee();
    employee.EmployeeDetails(); // Only Employee Details is visible

    var hr= new HR();
    hr.EmployeeDetails();
    hr.SalaryDetails(); // Both EmployeeDetails() and 
                        // SalaryDetails() should be visible.

}
StepUp
  • 36,391
  • 15
  • 88
  • 148
Vikash
  • 11
  • 1

1 Answers1

0

This isn't really how inheritance is designed to work. If some derived classes will inherit only some methods from base class, then it would be violation of Liskov substitution principle. What is an example of the Liskov Substitution Principle?

But you can inherit interface. Let me show an example.

These are interfaces. Pay attention to IHr interface. IHr inherits IEmployee interface:

public interface IEmployee
{
    string GetEmployeeDetails();
}

public interface IHr: IEmployee
{
    string SalaryDetails();
}

And its concrete implementations:

public class Employee : IEmployee
{
    public string GetEmployeeDetails()
    {
        return "Employee. EmployeeDetails";
    }
}

public class Hr : IHr
{
    public string GetEmployeeDetails()
    {
        return "Hr. EmployeeDetails";
    }

    public string SalaryDetails()
    {
        return "Hr. SalaryDetails";
    }
}

And you can use them like this:

IEmployee employee = new Employee();
employee.GetEmployeeDetails();

IHr hr = new Hr();
hr.SalaryDetails();
hr.GetEmployeeDetails();    
StepUp
  • 36,391
  • 15
  • 88
  • 148