Home  >  Article  >  Java  >  Why do interfaces not have constructors in Java, but abstract classes have constructors?

Why do interfaces not have constructors in Java, but abstract classes have constructors?

PHPz
PHPzforward
2023-09-13 18:09:031495browse

Why do interfaces not have constructors in Java, but abstract classes have constructors?

Constructor is used to initialize non-static members of a specific class relative to the object.

Constructor in the interface

  • Interface in Java does not have a constructor, because all data members in the interface are by default public static final , they are constants (assigned at declaration time).
  • There are no data members in the interface that can be initialized through the constructor.
  • In order to call a method, we need an object. Because the method in the interface has no body, there is no need to call the method in the interface.
  • Since we cannot call methods in the interface, there is no need to create an object for the interface and there is no need to include 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 class

  • ClassThe purpose of the constructor is to initialize fields, but not to build objects.
  • When we try to create a new instance of abstract super class, the compiler gives an error.
  • However, we can inherit an abstract class and use its constructor to control it 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

The above is the detailed content of Why do interfaces not have constructors in Java, but abstract classes have constructors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete