Page 151 - การเขียนโปรแกรมบนมาตรฐานเปิด
P. 151

151


                                                                                                          ็
               string studentID = "S001";         คือ การก าหนดค่าของ attribute studentID  ให้มีค่า "S001"; และเปน
                                                                ข้อมูลชนิด String


               Student student = new student();  คือ การสร้าง object student จาก class student โดยไม่มีการส่งค่า

                                                                argument

               System.out.println("##Default Constructor##");


               System.out.println("Student ID ="

               + StudentID + "\nGrade = " + Student.grade);


                 คือ การแสดงผลตัวแปร Student ID และข้อมูล grade จาก class Student แต่เนื่องจากไม่มีการสร้าง
               Constructor ไว้ จึงท าให้ compiler สร้าง default Constructor ให้โดยอัตโนมัติ จึงได้ค่าเริ่มต้นของ grade

               เป็น 0.0



               เมื่อท าการรันผลโปรแกรมจะได้ผลดังนี้
















               ตัวอย่างของโปรแกรมที่มีการใช้งาน Constructor มีดังนี้
   146   147   148   149   150   151   152   153   154   155   156