Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of Abstraction and Polymorphism in Java [duplicate]

I was going through the concepts of abstraction in Java.

These are my understandings:

  1. Abstraction is the method of presenting the signature of functions and hiding the implementation, leaving it to the users who can implement/extend the interface/abstract class.
  2. This way we can achieve greater scope for less modification of code, re-usability.
  3. We can closely relate the objects in real time to objects in program code.

These are my questions:

  1. When an abstract class can behave like an interface when all the methods are made abstract, why do we need interface separately? Please explain with an example for better understanding.

  2. Can we likely call Abstract class = Interface + Inheritance on a functionality basis? Because we can achieve the functionality of interface and inheritance together with Abstract class.

like image 804
user3725074 Avatar asked Apr 16 '15 12:04

user3725074


1 Answers

Simply saying: interface is a contract, abstract class is skeletal implementation. (Additionally, in Java interfaces are mostly used because it's not possible to extend multiple classes.)

Contract says what, implementation says how.

Example of interface: java.util.List. It has all methods that any list should have: add(), size(), indexOf() and so on.

Example of abstract class: java.util.AbstractList. Though it has many abstract methods, some List methods, that don't depend on the way elements are stored in the concrete list, are implemented there (addAll(), equals(), toString() and others). To create complete implementation, not all List methods should be implemented, thus making implementor's work easier.

like image 182
Alex Salauyou Avatar answered Sep 25 '22 10:09

Alex Salauyou