Difference between Abstract class and Interface in Java
The term Abstraction means that hiding the internal implementation of the feature and only showing the functionality to the users. That means an Abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. It cannot be instantiated, it can be only used as super class by its subclasses. These methods are simply function definitions that serves to tell the developer that the method must be implemented in a child class. Abstract classes are used to create template for its sub classes, it can capture common characteristics of subclasses.
Interface is a type which contains only the signatures of methods, delegates or events and it has no implementation. Implementation of the methods is done by the class that which implements the interface . It is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface . So if a class is implementing an interface, it says to the outer world that it provides specific behaviour .
The key technical differences between an abstract class and an interface are:
- Abstract class can have abstract and non-abstract methods whereas an Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
- Abstract classes can have constants, members, method stubs (methods without a body) and defined methods whereas interfaces can only have constants and methods stubs.
- Abstract classes can have constructors but interfaces can’t have constructors.
- Abstract classes methods can have access modifiers with any visibility, but interface methods are implicitly public and abstract.
- Abstract classes can have main method so we can run it whereas Interface do not have main method so we cannot run it.
- Abstract class can extends one other class and can implement one or more interface but an Interface can extends to one or more interfaces only
- A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).
- When compared to Interface, Abstract class is faster than interface because Interface is somewhat slower as it takes some time to find implemented method in class
- In abstract class keyword "abstract" is mandatory to declare a method as an abstract whereas in an interface keyword "abstract" is optional to declare a method as an abstract