Difference between Abstract Class and Interface
There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s have a look below.
| Abstract Class | Interface |
| An abstract class can have abstract, non-abstract, default, and static methods. | An interface can have only abstract methods. |
| It extend another java class and implement multiple java intfaces. | The interface extends another interface only. |
| It can have class members like public, private, protected, etc. Example: abstract class Student { private String name; public void setName(String n) { name=n;} public String getName() { return(name); } } | The interface is public by default, and we cannot declare it private or protected. Interface Calculate { double veg=25.50; intnon_veg= 55; int add(veg, non_veg) } |
| It may contain non-final variables. | Variables in the interface are declared final by default. |
| It can have a final, non-final, static, and non-static variable. | It has only static and final variables, but the function is non-static by default. We can’t declare a function as static. |
| It provides the implementation of the interface. | It cannot provide the implementation of the Abstract class. |
| It can be extended using the keyword “extends.” | It can be implemented using the keyword “implements.” |
| We can define a constructor in the abstract class if we can’t define any constructor, the compiler will create a constructor by default. | We can’t create a constructor inside an interface, and not even created by the compiler by default. |
| Abstratc class achives partial abstraction. | Interface achieves fully abstraction. |
Example to illustrate the working of Abstract class and Interfaces in java.
//Creating an interface that has 4 DMAS methods
interfaceinterfaceDemo
{
//methods are by default, public and abstract
void add();
void sub();
voidmul();
void div();
}
//Creating an abstract class that provides the implementation of one method of interfaceDemo
abstractclass Demo implementsinterfaceDemo
{
publicvoid add()
{
System.out.println("Add method");
}
}
//Creating a subclass of abstract class
classDmasextends Demo{
publicvoid sub()
{
System.out.println("Subtract Method");
}
publicvoidmul()
{
System.out.println("Multiplication Method");
}
publicvoid div()
{
System.out.println("Division Method");
}
}
//Creating a class that calls the methods of interfaceDemo
publicclassAbstractInterfaceDemo {
publicstaticvoid main(String args[]){
interfaceDemo a=newDmas();
a.add();
a.sub();
a.mul();
a.div();
}
}
