Benefits of Abstraction and Polymorphism in Java

I was looking at the concept of abstraction in Java.

This is my understanding:

  • Abstraction is a method of representing the signature of functions and hiding the implementation, providing it to users who can implement / extend the interface / abstract class.
  • Thus, we can achieve more for less code modification, reuse.
  • We can closely associate objects in real time with objects in program code.

These are my questions:

  • When an abstract class can behave like an interface, when all methods become abstract, why do we need an interface separately? Please explain with an example for a better understanding.

  • Is it possible to call functionality the functionality of Abstract class = Interface + Inheritance? Because we can achieve interface functionality and inheritance with an abstract class.

+6
source share
1 answer

Simply put: an interface is a contract, an abstract class is a skeletal implementation. (In addition, Java interfaces are mainly used because it is not possible to extend multiple classes.)

The contract says that, as stated in the implementation.

Interface example: java.util.List . It has all the methods that any list should have: add() , size() , indexOf() , etc.

An example of an abstract class: java.util.AbstractList . Although it has many abstract methods, some List methods are applied there that do not depend on how the elements are stored in a specific list ( addAll() , equals() , toString() and others). To create a complete implementation, not all List methods must be implemented, which makes it easier to work with developers.

+2
source

Source: https://habr.com/ru/post/985263/


All Articles