I'm struggling to understand the overall use of Abstraction in Java.
I have been working off an example in this link: https://javatutorial.net/java-abstraction-example I understand the implementation of it but I don't understand why its even necessary. Why is their a calculateSalary method made in the Employee class if they are just going to made again in the 2 subclasses?
The overall use of abstraction is decoupling. To work with an Employee
, one does not need to know the implementation, only the interface and its contracts. This is, for example, used for Collections.sort(List<T> list)
: the programmers of Collections.sort(...)
did not need to know the implementation of a specific list in order to sort it. This provides the benefit that the implementation support future code that conforms to the List
interface. This question is related in that respect (#selfPromotion). Less coupling leads to less friction and overall less fragile code.
That said, the example you provided is a poor one since it violates the Single Responsibility Principle: It is not the responsibility of an Employee
instance to calculate the salary. For this, we should have a separate object that calculates the salary, based on an Employee
-instance and some hours worked. Internally, this Uber-calculator could use a Chain of Responsibility, which hold one Calculator
per Employee
-Implementation, decoupling the Employee
from how their salary is calculated. This provides the added benefit of extensibility and flexibility: if the way a salary is calculated changes (e.g. maybe the company switches policy so that each FullTimeEmployee
earns the same salary, or maybe the company wants to calculate the salary on a by-week instead of a by-month basis), other services using the FullTimeEmployee
say unaffected).