ทางแก้เลยต้องใช้ interface เข้าช่วย
หลักการมีอยู่ว่าต้องขึ้นต้นด้วยคำว่า interface เช่น
interface A {
}
และกฏมีอีก 2 ข้อใหญ่ๆ คือ
1. หากมีการกำหนดตัวแปร ให้กำหนดค่าเริ่มต้นไว้เลย เช่น int x = 0;
2. หากมีการสร้าง method ไม่ต้องเขียน body เช่น void print(); เท่านี้พอ
ส่วนคลาสอื่นๆ หากต้องการใช้งานต้องทำการใช้ implements เช่น
class B implements A {
}
ตัวอย่างโค้ดจริง
ผลการทำงานpackage myPackage; interface I { int x = 10; public void print(); } public class UseInterface implements I { public void print() { System.out.println("Print Output"); } public static void main(String[] args) { new UseInterface().print(); } }
Print Output
ไม่มีความคิดเห็น:
แสดงความคิดเห็น