建構子用於初始化特定類別相對於物件的非靜態成員。
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中文網其他相關文章!