Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

WHY Abstract when we have Inheritance n interface

 
sandeep putta
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WHY Abstract when we have Inheritance n interface. cant we do the same functionality with inheritance and interface with out Abstract
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With abstract classes, you can choose to implement some of the functionality, while leaving other functionality abstract. This way code that should be shared by many implementations can already be provided.

The Collections framework uses both: interfaces for defining the functionality, and abstract classes implementing those to provide basic functionality. For instance, when you want to write a new Collection implementation, you can just extend AbstractCollection and don't have to worry about methods as addAll, removeAll, containsAll and retainAll.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not really adding anything new here -- just providing an illustration of what Rob described above.

Suppose an interface declares 20 methods. If you implement this, you need to write functionality for 20 methods. But an abstract class could implement that interface and provide basic functionality for 16 of these methods, leaving the other 4 abstract. This way, it's done most of the work for you. So instead of implementing the interface, you can extend the abstract class, and you only need to write functionality for 4 methods instead of 20. (Of course, if you don't like the way the abstract class has implemented the other methods, you can override these with your own functionality.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic