Open In App

Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?

Prerequisite: Interface and Abstract class in Java.

A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created.



Why interfaces can not have the constructor?




// Java program that demonstrates why
// interface can not have a constructor
 
// Creating an interface
interface Subtraction {
 
    // Creating a method, by default
    // this is a abstract method
    int subtract(int a, int b);
}
 
// Creating a class that implements
// the Subtraction interface
class GFG implements Subtraction {
 
    // Defining subtract method
    public int subtract(int a, int b)
    {
        int k = a - b;
        return k;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Creating an instance of
        // GFG class
        GFG g = new GFG();
        System.out.println(g.subtract(20, 5));
    }
}

Output

15

In the above program, we have created an interface Subtraction which defines a method subtract(), whose implementation is provided by the class GFG. In order to call a method, we need to create an object, since the methods inside the interface by default public abstract which means the method inside the interface doesn’t have the body. Therefore, there is no need for calling the method in the interface. Since we cannot call the methods in the interface, there is no need for creating the object for interface and there is no need of having a constructor in it.

Why abstract classes have a constructor




// A Java program to demonstrates
// an abstract class with constructors
 
// Creating an abstract class Car
abstract class Car {
 
  // Creating a constructor in
  // the abstract class
    Car() {
      System.out.println("car is created");
    }
}
 
// A class that extends the
// abstract class Car
class Maruti extends Car {
 
  // Method defining inside
  // the Maruti class
    void run() {
      System.out.println("Maruti is running");
    }
}
 
class GFG {
 
    public static void main(String[] args)
    {
        Maruti c = new Maruti();
        c.run();
    }
}

Output
car is created
Maruti is running

 


Article Tags :