One of the basic Java interview question is what is the difference between abstract class and interface. If you are a beginner in Java, you can not avoid this question in any Java interview to test your knowledge on Java OOPs concepts. In this short tutorial I will write down the difference between abstract class and interface in Java. Also there is few simple examples for abstract class and interface.
The below table presents the key differences:
Abstract Class in Java |
Interface in Java |
|
1 | An abstract class can have instance methods that would have default implementation | Interface is implicitly abstract and can not have any default method implementation. But, with Java 8, interfaces can have method implementation using the default keyword. |
2 | Abstract class doesn’t support multiple inheritance. | Interface supports multiple inheritance. |
3 | Abstract class can have constructors. | Interfaces can not declare a constructor. |
4 | Abstract class can extend only one class or one abstract class at a time | Interface can extend any number of interfaces at a time |
5 | abstract class can extend from a class or from an abstract class | interface can extend only from an interface |
6 | abstract class can have both abstract and concrete methods | interface can have only abstract methods |
7 | A class can extend only one abstract class | A class can implement any number of interfaces |
8 | In abstract class keyword ‘abstract’ is mandatory to declare a method as an abstract | In an interface keyword ‘abstract’ is optional to declare a method as an abstract |
9 | Abstract class can have protected , public and public abstract methods. There is no implicit behavior for the members. | Interface can have only public abstract methods. The members of interface are implicitly public by default. Also interfaces can not have static methods. |
10 | Abstract class can have static, final or static final variable with any access specifier | Interface members are implicitly static and final by default. |
Abstract Class Example
public abstract class AbstractClass{ public int i = 10; public void abstract abstractMethod(); public void methodImpl(){ System.out.println("Default Method Implementation"); } } class ClassImpl extends AbstractClass{ public void abstractMethod(){ System.out.println("Method Implementation in Sub Class"); } }
Interface Example
public class InterfaceExample{ public static final i = 10; //public, static, final keywords are optional. public void abstractMethod(); //This method is implicitly abstract public void methodImpl(){ // This method is not legal. Method implementation not allowed in interfaces. } }