Monday, December 3, 2012

Similarities and Differences [Interface and Abstract Class]

Interface and Abstract Class

Similarities:
The only similarity between Interface and Abstract class is that both can not be instantiated.

Differences:
  1. An abstract class can have methods with implementation, to provide some default behavior.An interface can not have any implementation.
  2. All the variables in the interface are final by default. An abstract class can have non-final methods.
  3. All the methods in an interface are public by default. An abstract class can have protected and ...
  4. If we want to implement an interface we would use implements. For an abstract class we would use extends.
Whats the need of interface when we have Abstract class?

Why there is a need of Abstract class in Java

Many developers think that Abstract class is a class which can not be instantiated, but can be extended into subclasses. that is whose object can not be created, but there is more to it

Why we need an abstract class?
Abstract class does not have any real time object, but it is required to provide some common characteristics
Example Vehicle - Car, truck,
Car - Maruti, Hyundai, tata Nano

Vehicle is the abstract class, it has tires and steering, car has 4 tyres , truck has 6 or 8 tyres
Car is abstract class, it has tires, steering, dashboard, headlight etc.