Abstract class vs interface in java

Abstract class and interface both of these are used to achieve abstraction where the abstract method can be declared. Abstract class and interface both of these cannot be instantiated. But there are many variations between abstract class and interface which are given below.  

Abstract class Interface
It can have method body (non-abstract methods) i.e. Abstract class can consists of abstract and non-abstract methods. It have only abstract methods. In Java 8 and higher versions, an interface can also consists of default and static methods.
It can have instance variables. It cannot have instance variables.
It can have constructor. It cannot have constructor.
It can have static methods. It cannot have static methods till Java 7 but since Java 8, an interface can also have static methods.
You can extends one abstract class and hence does not support multiple inheritance. You can implement multiple interfaces and hence support multiple inheritance.
An abstract class can implement an interface. An interfaces can not extends an abstract class.
An abstract class can extends another class as well as can implement an interface. An interfaces can extends another interface and can not extends an abstract or non abstract class.
An abstract class declared with abstract class. An interfaces declared with interface keyword.
The extends keyword is used to extend an abstract class by another class. The implements keyword is used to implement an interfaces by java class.

Example: Abstract Class

abstract class SubtractionTest {
 
    abstract void subtraction(int num1, int num2);
 
 }
 
public class Main extends SubtractionTest
{
    public void subtraction(int num1, int num2) {
        System.out.println(num1 - num2);
    }
 
	public static void main(String[] args) {
		SubtractionTest subtractionTest = new Main();
		subtractionTest.subtraction(150, 100);
	}
}

Output

50

Example: Interface

interface SubtractionTest {
 
    void subtraction(int num1, int num2);
 
 }
 
public class Main implements SubtractionTest
{
    public void subtraction(int num1, int num2) {
        System.out.println(num1 - num2);
    }
 
	public static void main(String[] args) {
		SubtractionTest subtractionTest = new Main();
		subtractionTest.subtraction(150, 100);
	}
}

Output

50

 

Java interview questions on interface and abstract class

Please follow and like us:
Content Protection by DMCA.com