1

I have four classes

Person
Employee
Manager
Boss

Employee extends Person
Manager extends Employee
Boss extends Manager

I have method:
Employee have method setSalary() { ... }

I want only Boss class to be able to change Employee's salary. not even Employee class nor Manager class only Boss class.

How can i do that ? I know there is way to use instanceof but dont know how

Miljan Rakita
  • 1,433
  • 4
  • 23
  • 44
  • If you need it only in Boss class, why do you declared in the parent classes? If for some reason you need it in the parent classes you could leave implementation of the method empty, you could declare all the classes abstract except boss, you could have an interface that is implemented only by the boss class... – cantSleepNow Apr 02 '16 at 09:47
  • 1
    possible duplicate: [Is there a way to simulate the C++ 'friend' concept in Java?](http://stackoverflow.com/questions/182278/is-there-a-way-to-simulate-the-c-friend-concept-in-java) – Jorn Vernee Apr 02 '16 at 09:53
  • it's a bit strange, but you could check the caller class in setSalary, see http://stackoverflow.com/questions/11306811/how-to-get-the-caller-class-in-java – Turo Apr 02 '16 at 10:42

2 Answers2

2

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.

Anmol Gupta
  • 2,797
  • 9
  • 27
  • 43
0

I think it's possible but it will require using interfaces. You might find an answer here:

Can I limit the methods another class can call in Java?

Java: How to limit access of a method to a specific class?

Community
  • 1
  • 1
Adam Rice
  • 880
  • 8
  • 20