Skip to content

Instantly share code, notes, and snippets.

@danishsatkut
Last active August 22, 2016 08:08
Show Gist options
  • Save danishsatkut/c11cf03485ef9aa53a6d99ee54e67c72 to your computer and use it in GitHub Desktop.
Save danishsatkut/c11cf03485ef9aa53a6d99ee54e67c72 to your computer and use it in GitHub Desktop.
class Employee {
private String name;
private String position;
public Employee(String name, String position) {
this.name = name;
this.position = position;
}
public Employee changeName(String name) {
return new Employee(name, this.position);
}
public Employee changePosition(String position) {
return new Employee(this.name, position);
}
}
class SalaryCalculator {
private Employee employee;
public SalaryCalculator(Employee emp) {
this.employee = emp;
}
public int calculateSalary() {
if (employee.getPosition().matches("Senior(.*)")) {
return 10000;
} else {
return 5000;
}
}
}
class SalaryProgram {
// Calling function
public static void main(String[] args) {
Employee jane = new Employee('Jane', 'Senior Programmer');
// Injected dependency jane in SalaryCalculator constructor
SalaryCalculator calculator = new SalaryCalculator(jane);
calculator.calculateSalary(); // Return 10000
// IMPORTANT: This does not change the employee private variable of calculator.
jane = new Employee('Other Jane', 'Junior Programmer');
// Encapsulation is not broken
calculator.calculateSalary(); // Still returns 10000
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment