If your Employee class has a method setSalary(..);
, then there is no way you can avoid employee from calling it's setSalary(..);
method. A private method can also be called inside the class by another method of that class.
What you can possibly do is: set the visibility of setSalary(..);
to package level and keep only Employee
and Boss
in the same package, and all other in another package. And take care that setSalary(..);
for any Employee
is called only inside some method in Boss
You would have a method in Boss
something like:
public class Boss extends Employee {
public void setSalaryFor(Employee employee, int salary) {
employee.setSalary(salary);
}
}
And your Employee class will have method as:
public class Employee extends Person {
private int salary;
//Package visibility
void setSalary(int salary) {
this.salary = salary;
}
}
This way, outside your package which only have Employee
and Boss
, Employee
will not be able to call setSalary(..);
method and only way to update salary of the employee will be to call public method of Boss
and passing salary and employee as the arguments to it.