构造函数用于初始化特定类相对于对象的非静态成员。
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)); } }
k value is:30
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()); } }
Manager Name is:Adithya Salary is:50000.0
以上是为什么在Java中接口没有构造函数,而抽象类有构造函数?的详细内容。更多信息请关注PHP中文网其他相关文章!