This is one of the most frequently asked questions in the interview. Many interviewers will not leave this topic. So let’s see the difference between them
- The main difference is that the Interfaces are implicitly abstract and cannot have implementation, whereas an abstract class can have a concrete class.
- Interface is implemented using the “implements” keyword. Abstract class can be extended using the “extends” keyword.
- All the variables in an Interface are by default Static and Final whereas an Abstract can have other access specifiers as well.
- The methods in an Interface are by default Public but Abstract class can have non-public(private, protected..) methods too.
- An Interface can extend other Interfaces only but an Abstract class can extend other java classes and implement interfaces.
- Interfaces are absolutely abstract and cannot be instantiated, als0 an abstract class cannot be instantiated but it can be run if it has a main() method. The below code will get executed successfully and will give you the output as “Inside Main method” and followed by “Abstract method called”. So Abstract class can have a main method but still you cannot instantiate the class.
abstract class AbstractEg { public static void main(String aa[]) { System.out.println("Inside main method"); disp(); } abstract void disp1(); public static void disp() { System.out.println("Abstract method called"); } }
- A Java class can implement multiple interfaces but can extend only one abstract class.
Before ending this, there is another question regarding its usage.
When to use Interface and Abstract class?
You can use interfaces when you want a full implementation and use abstract classes when you want partial implementation for your design.
Harish M says
Nice tutorial , clarifying my doubts on diff between abstract and Interface. And could you mention a specific real-time use case on difference between Abstract class and Interface where it would suit exactly?
javainterviewpoint says
In real-time, use an Abstract class when you have a application which needs to abide by a contract and has some common functionality. Lets say if your application is an WriterUtility, for writing we first need to open the file before writing and close the file after completion, then you can have concrete methods like openFile() and closeFile().
On the other hand, if your application doesn’t have any common functionality and just need to follow the contract then go for an Interface. In real-time Db Connection Utility will be an interface where you will have skeleton for getting connection which can be oracle, mysql, db2 etc. The implementation class will provide the functionality for the skeleton methods.