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

Vaibhav Gupta
2 min readMay 1, 2022

--

Interface and Abstract Classes are among the OOPs concept of JAVA programming language. But when we should use which one, actually depends on the situation and the need.

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.

Hope you like this blog. Feel free to suggest/query in the comments section.

Keep Learning :)

--

--

Vaibhav Gupta
Vaibhav Gupta

No responses yet