-2

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?

  • As said in that link `Abstraction is a process of hiding the implementation details from the user` So `calculateSalary()` abstract function is defined in abstract `super class` so that it's `sub class` (which is extending Employee abstract class) could defined as per their `algorithm/calculation` and these `algorithm/calculation` will be hidden from other `entities/user` – Varad Mondkar Feb 09 '19 at 19:25
  • All good texts on object-oriented programming and design talk about abstraction. Which ones have you studied? – Lew Bloch Feb 09 '19 at 20:00
  • @VaradMondkar the benefit of abstraction is not some kind of hiding (which implies some sort of of (false) secrecy). The real benefit is less coupling and, in return, less friction. I recommend to watch [this youtube snippet of Uncle Bob talking about polymorphism and decoupling (the relevant part is about 15 minutes long)](https://youtu.be/TMuno5RZNeE?t=37m43s). – Turing85 Feb 10 '19 at 07:50
  • @Turing85 Thank you for correcting and sharing the video. – Varad Mondkar Feb 10 '19 at 08:01

1 Answers1

3

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).

Turing85
  • 18,217
  • 7
  • 33
  • 58