Tuesday, 10 March 2015

Difference between abstract class and interface

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

  1. abstract keyword is used to create an abstract class and it can be used with methods also whereasinterface keyword is used to create interface and it can’t be used with methods.
  2. Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class whereas subclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface.
  3. Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
  4. Abstract classes can have constructors but interfaces can’t have constructors.
  5. Abstract class have all the features of a normal java class except that we can’t instantiate it. We can useabstract keyword to make a class abstract but interfaces are a completely different type and can have only public static final constants and method declarations.
  6. Abstract classes methods can have access modifiers as public, private, protected, static but interface methods are implicitly public and abstract, we can’t use any other access modifiers with interface methods.
  7. A subclass can extend only one abstract class but it can implement multiple interfaces.
  8. Abstract classes can extend other class and implement interfaces but interface can only extend other interfaces.
  9. We can run an abstract class if it has main() method but we can’t run an interface because they can’t have main method implementation.
  10. Interfaces are used to define contract for the subclasses whereas abstract class also define contract but it can provide other methods implementations for subclasses to use.




No comments:

Post a Comment