This is a simple scenario in a office between employee and his manager.
In actual world manager can manage many employees but for simplicity sake
in here consider the situation between one employee and his manager
in here both manager and employee have name attribute
only employee has a designation attribute
For the above scenario i created this Class diagram
implement the above scenario using java code as shown below ( please note this code as pseudo code and also orchestration code not include,syntax can be wrong )
class Manager{
private String name;
private Employee employee;
//assign name and create association link between employee
Manager(Employee employee,String managerName ){
this.employee = employee;
this.name = managerName;
}
//manager can change his name
private void changeName(String managerName){
this.name = managerName;
}
//only manager can change Employee designation
private void changeEmpDesignation(String empDesignation){
this.employee.changeDesignation(empDesignation);
}
}
/* --------------------------- */
class Employee{
private String name;
private String designation;
Employee(String name ,String designation ){
this.designation = designation;
this.name = name;
}
//only Employee can change his name
private void changeName(String empName){
this.name = empName;
}
//only manager can change Employee designation
public void changeDesignation(String empDesignation){
this.designation = empDesignation;
}
}
But
Employee.changeName()
method private for prevent the manager changing employee name is it correct approach?changeDesignation()
method is in Employee
class can access both Employee
class it self and also Manager
class this means
manager can change designation of the employee and employee can also change his/her designation, I want to prevent this happening and make manager is the only one be able to change employee designation.how to implement it in code?Well, there are some things to consider in this scenario. Even though it makes a lot of sense if you think as real world entities, it’s usually not a good OO practice to let an object change another object’s state.
That being said, if you don’t want any other class to change one class’ property you should make the field private and provide no setter at all.
As for the designation, you can’t really stop an object from modifying its properties, unless it’s final, but then the manager couldn’t change it either.
I suppose you could have an Designation class, and make it so that only the manager can instantiate it. But even then the employee could set it to null.
Or you could have the Designation class hold the reference to one or many employees, then only the manager could access the designation objects.
As I said, I think that’s one of those times where OO modeling doesn’t really fit the real world. Classes should be responsible for its own state, and hold its own set of rules for any state changes. Any other class should be able only o ask or request a change.
Hope it helps!