6

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.

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
user3725074
  • 103
  • 1
  • 3
  • This question should answer your questions: http://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class – Leandro Carracedo Apr 16 '15 at 12:57
  • And here is an answer as to why the decision was made to not allow multiple implementation-inheritance in java: http://stackoverflow.com/questions/995255/why-is-multiple-inheritance-not-allowed-in-java-or-c – jmrah Apr 16 '15 at 13:03

1 Answers1

2

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.

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67