Constructor ใช้เพื่อ initialize non-static members ของคลาสเฉพาะเจาะจงกับ object
Constructor ใน Interface
- Interface ใน Java ไม่มี constructor เพราะ data members ทั้งหมดใน interfaces เป็น public static final โดย default พวกมันคือ constants (กำหนดค่าตอนประกาศ)
- ไม่มี data members ใน interface ที่ต้อง initialize ผ่าน constructor
- เพื่อเรียกเมธอด เราต้องมี object เนื่องจากเมธอดใน interface ไม่มี body จึงไม่จำเป็นต้องเรียกเมธอดใน interface
- เนื่องจากเราไม่สามารถเรียกเมธอดใน interface ได้ จึงไม่จำเป็นต้องสร้าง object สำหรับ interface และไม่จำเป็นต้องมี constructor
ตัวอย่าง 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));
}
}
ผลลัพธ์
k value is:30
Constructor ใน Class
- วัตถุประสงค์ของ constructor ใน class คือใช้ initialize fields ไม่ใช่สร้าง objects
- เมื่อเราพยายามสร้าง instance ใหม่ของ abstract superclass คอมไพเลอร์จะให้ error
- อย่างไรก็ตาม เราสามารถ inherit abstract class และใช้ constructor ของมันได้โดยการตั้งค่าตัวแปรของมัน
ตัวอย่าง 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());
}
}
ผลลัพธ์
Manager Name is:Adithya Salary is:50000.0