In Java, why do we need interface when we have abstract classes.. ?

When to use Interfaces:

  • Achieving 100% abstraction. By using abstract classes, we can achieve partial abstraction if it has abstract and non abstract methods whereas by using interfaces, we achieve complete abstraction as Interfaces always have abstract methods.
  • In interface, the variables declared are static and final by default. So used when we does not want any implementing class to change the variable value.
  • We can achieve multiple inheritance in JAVA using interface. Suppose that there are 2 interfaces — Person and Programmer. So if we want to create a class Employee who is both a person and programmer. We can do so by implementing both Person and Programmer as — class Employee implements Person, Programmer{}
  • Interfaces are more flexible. Consider an example when you don’t want to force your clients to implement all methods of one interface. In this case, you can segregate your interface into multiple interfaces (Interface Segregation Principle).

When to use Abstract Classes:

  • When we want to share some common functionality to all classes then create an abstract class. This will also help in updating the common functionality in only 1 base class if any update is required.
  • When you want to declare non static and non final fields. This enables you to create methods for modifying those fields.
  • When you want to declare data members with different access modifiers like private, protected, etc. Interfaces data members are always public by default.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store