Abstract Class vs Interface in Java

Let’s discuss Abstract Class vs Interface in Java. An  Interface in Java differs from an abstract class because an interface is not a class. An interface is essentially a type that can be satisfied by any class that implements the interface.
An abstract class is a class and other classes need to extends an Abstract class. Abstract classes are typically used as base classes for extension by subclasses.

If you need to separate an interface from its implementation, use an interface. If you also need to provide a base class or default implementation of the interface, add an abstract class (or normal class) that implements the interface.

 

Abstract Class vs Interface in Java

There is much difference between Interface and Abstract class, Please note the following points.

  • Interfaces are a pure abstraction  in nature .It can not have an implementation at all but Abstract class can have default method implementation.
  • In Interface subclasses use implements keyword to implement interfaces and should provide an implementation for all the methods declared in the interface but in Abstract Class subclasses use extends keyword to extend an abstract class and they need to provide the implementation of all the declared methods in the abstract class unless the subclass is also an abstract class.
  • The interface  can not have the constructor and Abstract class can have the constructor.
  • Interfaces are not the Java classes and Abstract classes are almost same as java classes except you can not instantiate it.
  • Interface methods are by default public. you can not use any other access modifier with it and Abstract class methods can have any access modifier.
  • Interface do not have main() method but  Abstract classes can have main() method.
  • The interface can extend to one or more interfaces  but an Abstract class can extend one other class and can implement one or more interface.
  • If you add the new method to the interface, you have to change the classes which are implementing that interface but If you add the new method to an abstract class, you can provide a default implementation of it. So you don’t need to change your current code.

 

Video Tutorial of Automation Testing:

 

Example of Interface, Abstract Class

In the below example we are declaring an interface, Which is later extending the Abstract class than creating the subclass of the Abstract Class.

Output:

Hi, I am from First Method
Hi, I am from Second Method
Hi, I am from third method

 

0 Comment

Leave a Reply