Implicit Classes เช่น VarArg และ Enum

เราสามารถสร้าง Data Type ขึ้นมาใหม่เองได้ เช่น Data Type ของวันในสัปดาห์
หรือ Data Type ของดวงดาวในระบบสุริยะ เช่น

enum Day {

         Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saterday

}

โดยสามารถนำไปใช้งานได้ดังนี้

Day day = null;//ประกาศตัวแปรของ Day เป็น null
day = Day.Monday;//Assign ค่า
System.out.println(day);//แสดง Monday

โดยที่ compiler จะแปลง enum ออกมาเป็น class ให้และมี method ที่สำคัญเช่น

day = Day.valueOf("Sunday");//หากไม่พบ Sunday จะเกิด error

for (Day d:Day.values())//วนลูปแสดงค่าสมาชิกทั้งหมด
            System.out.println(d);

String name = d.name();//แปลงเป็น String
int ord = d.ordinal();//ลำดับที่ประกาศโดยเริ่มจาก 0

นอกจากนี้ยังสามารถประกาศ Constructor ได้อีกด้วยเช่น

enum Level {

        int level;
        Beginner(1), Intermediate(2), Advance(3);
        Level(int level) {

               this.level = level;
         }

}

สำหรับ modifier ของ constructor จะเป็นได้คือ private เท่านั้นซึ่งหากไม่ระบุ
compiler จะถือว่าเป็น private

VarArg

เราสามารถประกาศ method ที่รับ parameters ที่มีำจำนวนไม่แน่นอนได้ดังนี้

void test(int...num) {}

ทำให้สามารถเรียกใช้โดย

test(1,2,3,4,5,6) หรือ test(0,1,2); ได้

ซึ่ง num ที่ได้จะถูก compiler แปลงให้เป็น Array นั่นเอง

void test(int...num) {

       for(int i:num)
            System.out.println(i);

}

test(1);//1
test(1,2);//1,2
test(1,2,3);//1,2,3

แต่การประกาศ VarArg ก็มีข้อจำกัดคือมีได้แค่อันเดียวและต้องเป็น parameter 
ที่อยู่ท้ายสุดเช่น

void test(int i, int...num){}//Correct!
void test(int...num, int i){}//Compile Error!
void test(int...num, int...i){}//Compile Error!

สอนพื้นฐาน Java
Line: wizarud
Gmail: [email protected]