IJAS
IJAS

Reputation: 1

How to access part of the members of base class

I have a base class

class Administrator()
    {
         void addEmployee(){ some code };
         void Salary_PaySlip() { some code }; 
    }
class HR: Administrator
    {
            // make use of addEmployee()
    }
class Accountant: Administrator
    {
            // make use of void Salary_PaySlip()
    }

This is just an example.

Here I want Accountant use the method Salary_PaySlip() only. The method addEmployee() should not be accessible by Accountant. Same way class HR should only have access to the addEmployee() method.

Can Someone help me to solve this?

Thanks in Advance

Upvotes: 0

Views: 49

Answers (1)

Bruno Belmondo
Bruno Belmondo

Reputation: 2357

Your problem can be sumarized as the Single Responsibility Principle which is quite related to the Interface Segregation Principle (I suggest you check the SOLID principles of object oriented design : https://en.wikipedia.org/wiki/SOLID_(object-oriented_design))

You created a class administrator which can add employees and PaySlip at the same time. However you want to segregate who is authorized to use some part of your class. This is the sign that this class should be split in two different classes. One for each method.

You will then be able to create your "client" classes (those who use the methods). I suggest that you use composition rather than inheritance to get access to your administrator parts in the end as it's not sure it makes sense to have this inheritance link.

Sample code which is of course not relevant yet (but can't do better without more info)

public class EmployeeAdministrator()
{
    public void addEmployee(){ some code };
}

public class SalaryAdministrator()
{
    public void Salary_PaySlip() { some code };
}

public class HR 
{
    public EmployeeAdministrator Administrator { get; }
    // make use of addEmployee()
}

class Accountant
{
    public SalaryAdministrator Administrator { get; }
    // make use of void Salary_PaySlip()
}

Upvotes: 2

Related Questions