Last active
August 22, 2016 08:08
-
-
Save danishsatkut/c11cf03485ef9aa53a6d99ee54e67c72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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