Why an interface doesn't have a constructor whereas an abstract class have a constructor in Java?

JavaObject Oriented ProgrammingProgramming

A Constructor is to initialize the non-static members of a particular class with respect to an object.

Constructor in an interface

  • An Interface in Java doesn't have a constructor because all data members in interfaces are public static final by default, they are constants (assign the values at the time of declaration).
  • There are no data members in an interface to initialize them through the constructor.
  • In order to call a method, we need an object, since the methods in the interface don’t have a body there is no need for calling the methods in an interface.
  • Since we cannot call the methods in the interface, there is no need of creating an object for an interface and there is no need of having a constructor in it.

Example 1

interface Addition {
   int add(int i, int j);
}
public class Test implements Addition {
   public int add(int i, int j) {
      int k = i+j;
      return k;
   }
   public static void main(String args[]) {
      Test t = new Test();
      System.out.println("k value is:" + t.add(10,20));
   }
}

Output

k value is:30

Constructor in a class

  • The purpose of the constructor in a class is used to initialize fields but not to build objects.
  • When we try to create a new instance of an abstract superclass, the compiler will give an error.
  • However, we can inherit an abstract class and make use of its constructor by setting its variables.

Example 2

abstract class Employee {
   public String empName;
   abstract double calcSalary();
   Employee(String name) {
      this.empName = name; // Constructor of abstract class  
   }
}
class Manager extends Employee {
   Manager(String name) {
      super(name); // setting the name in the constructor of subclass
   }
   double calcSalary() {
      return 50000;
   }
}
public class Test {
   public static void main(String args[]) {
      Employee e = new Manager("Adithya");
      System.out.println("Manager Name is:" + e.empName);
      System.out.println("Salary is:" + e.calcSalary());
   }
}

Output

Manager Name is:Adithya
Salary is:50000.0
raja
Published on 06-Jun-2019 15:06:05
Advertisements