Difference Between Abstract Class And Interface In Java
Differentiation between abstract class and interface
Difference between abstract class and interface are,
Abstract class | Interface |
Abstract class can hold abstract methods and non-abstract methods both. | Interface has only abstract methods. |
Abstract keyword is used to create an abstract class. | Interface keyword is used to create interface. |
Abstract class can contain static, non-static, final and non-final data members. | Interface has only static and final data members. |
Abstract class can contain static methods, main method and constructor. | Interface can’t contain static methods, main method or constructor. |
Abstract class can give the implementation of an interface. | Interface can't give the implementation of an abstract class. |
Abstract class can extends only one class at a time. | Interface can extend any number of interfaces at a time. |
Abstract class is used to achieve partial abstraction. | Interface is used to achieve full abstraction. |
Abstract class can extend from a class or from an abstract class. | Interface can extend only from an interface. |
For example
public abstract class Car{
public abstract void run();
}
|
For example
public interface Bike{
void run();
}
|
Similarity between Abstract class and Interface
- Both abstract class and an interface is used for abstraction in Java.
- We can’t instantiate both.
Let’s see an example of an abstract class and an interface, given below.
Code
- //Creating interface that has 4 methods
- interface Shape {
- void draw(); //bydefault, public and abstract
- void print();
- void show();
- void display();
- }
- //Creating an abstract class that provides the implementation of one method of shape interface
- abstract class Circle implements Shape {
- public void print() {
- System.out.println("Print image");
- }
- }
- //Create a subclass of an abstract class. Now, we need to provide the implementation of rest of the methods, given below-
- class Rectangle extends Circle {
- public void draw() {
- System.out.println("Draw image");
- }
- public void show() {
- System.out.println("Show image");
- }
- public void display() {
- System.out.println("Display image");
- }
- }
- //Creating a Exampletest class that calls the methods of shape interface-
- public class ExampleTest {
- public static void main(String args[]) {
- Shape a = new Rectangle();
- a.draw();
- a.print();
- a.show();
- a.display();
- }
- }
Output
In the example, mentioned above, we create an interface Shape, which has four methods. Create an abstract class Circle, which provides the implementation of one method of shape class. Afterwards, create a subclass of an abstract class Rectangle that provides the implementation of rest of the methods. Create an ExampleTest class, which calls the method of Shape interface.
Summary
Thus, we learnt that both abstract class and an interface are used for abstraction and also learnt their differences in Java with the example.