An abstract class and interface both are used to achieve the abstraction in Java, but there are some differences. In this blog we will see the difference between abstract class and an interface
Abstract class
- An abstract keyword using for creating the abstract class.
- An abstract keyword using for creating the abstract method.
- Can have the constructor. It will be called when you create the instance of the child class.
- Does not have the create the default method.
- Can have the non abstract method or concrete method.
- Can extends the another abstract class and implements the interface.
package com.samplecoder.abstraction;
public abstract class SampleAbstractClass {
SampleAbstractClass(){
// Constructor
}
public abstract void sampleAbstractmethod();
public void sampleConcreteMethod() {
System.out.println("concrete method in abstract class");
}
}
Interface
- An interface keyword using for creating the interface.
- By default, all the methods are abstract method. Not needed to use an abstract keyword for creating the abstract method.
- Does not have the constructor.
- Can have the default method. For backward compatibility.
- Does not have the concrete method. If you want to add the concrete method, that should be the default or static method.
- Can extends the other interface but cannot extend the any abstract class.
package com.samplecoder.abstraction;
public interface SampleInterface {
public void print(String arg);
}
Concrete method
Concrete method is a method which has the body of the method. The body of method start with “{” open curly brace and “}” close curly brace. You can see the sampleConcreteMethod method in a SampleAbstractClass class in this same blog. That is the example of concrete method.
One Comment on “Difference between abstract class and an interface”
Comments are closed.