05 February, 2009

Practical difference between Interface and Abstract class

Interface

Interface is used to collect similarities. Wherever we have to implement in the class means follow that similarities

Wherever we have to use (Real life scenario)

- Two person using same code but connection to the database methods only differ to each other. One person use sql based connection another one use oracle based connection. This type of scenario we can use Interface.
- A human and a parrot can both whistle, however it would not make sense to represent Humans and Parrots as subclass of a Whistle class, rather they would most likely be subclasses of an Animal class (likely with intermediate classes), but would both implement the Whistle interface.

What is Interface ?
  • The behavior of a class
  • All methods of an Interface are abstract methods.
  • They cannot have bodies
  • You cannot create an instance from an interface
  • An interface can only be implemented
  • This is the concept of encapsulation
  • During runtime, actual object instance is associated with the interface type
  • It needs only the interface at the compile time
  • Interface does not contain constructor
  • Multiple inheritance feature can be achieved through interface
  • Cannot be versioned.

Abstract Class
  • It is a class that contains one or more abstract methods
  • It may contain constructor but interface does not contain constructor.
  • In Interface all methods should be public but not in abstract class
  • Abstract class we can put sharable code
  • Its not Possible to create instance of Abstract class
  • It cannot be instantiated on it’s own, it must be inherited.
  • It can use One Overriding method
  • It can specify members that must be implemented in inheriting classes
  • A class can inherit only one abstract class
  • It enables us to place common instance behavior.
  • Offer versioning benefits.
  • Used for sharing common features among verious objects.

No comments: