ต.ย.โปรแกรมเชิงวัตถุ ชุดที่ 1
Home  Contents KMArticlesMembersSponsorsAbout us

ปรับปรุง : 2556-07-27 (ปรับคำอธิบายโค้ดใหม่)
OOP :: intro ch1-12 :: keyword & sign :: method calling :: series #1 :: series #2 :: series #3 :: pro_pmy
ขอบซ้ายขอบบน
Access level
1. Object แรกของ Class ที่ประมวลผลใน console ต้องชื่อ main
:: สร้างกล่อง 1 กล่อง และในกล่องมี object ทำหน้าที่พิมพ์ตัวอักษร "hello world"
:: ตัวอย่างนี้ภายในคลาสก็เสมือนกล่อง และในกล่องนี้ก็มีวัตถุ 1 ชิ้น
:: คลาส y สามารถเรียกใช้ main จากคลาส x ได้ สามารถเรียกแบบใช้ครั้งเดียว หรือกำหนด reference ก็ได้
    
      class x {
      public static void main(String args[])   {
        System.out.println("hello world");
      }
    }
    // ===
      class y {
      public static void main(String args[])   {
        String s[] = {};
        x.main(s);
        x a = new x();
        a.main(s);
      }
    }
    
2. เรียก object ใน class เดียวกัน โดยมองว่า class เสมือนกล่องเก็บ object
:: สร้างกล่อง 1 กล่องในกล่องมี 6 object และทุกวัตถุเป็น static แต่มี access level ต่างกัน
:: access level มี 4 แบบ ถ้าอยู่ใน class เดียวกันก็จะไม่เห็นความแตกต่าง เพราะจะต่างกัน ต่อเมื่ออยู่นอกคลาส หรือนอก package
:: กรณีนี้กำหนดให้ i เป็น static ถ้า i ไม่เป็น static หรือ main เป็น static วัตถุเดียว จะปรับโปรแกรมอย่างไร จึงจะให้ผลเหมือนเดิม
    
    class x {
      static int i = 1;
      public static void main(String args[])   {
        ok1(); ok2(); ok3(); ok4();
      }
      static void ok1()   {
        System.out.println(i++);
      }
      public static void ok2()   {
        System.out.println(i++);
      }
      protected static void ok3()   {
        System.out.println(i++);
      }
      private static void ok4()   {
        System.out.println(i++);
      }
    }
    // Result of this program
    // 1 2 3 4
    
3. เรียก object แบบ global กับ local ต้องระวัง
:: ใน class เดียวกันมีตัวแปรชื่อเดียวกันได้ หากแยกระหว่าง global กับ local
:: i++ หมายถึง ใช้ i ก่อนแล้วค่า i จึงจะเปลี่ยนไป
:: ++i หมายถึง เพิ่มค่าก่อน แล้วจึงใช้ค่าที่เพิ่มแล้ว ()
:: การย่อคำสั่งคำนวณทำได้หลายแบบ เช่น int i = 1; System.out.println((i+=5) + (i*=2)); // 18
    
    class x {
      int i = 1; // global variable
      public static void main(String args[])   {
        x a = new x();
        a.ok1(); a.ok2(); a.ok3(); a.ok4();
      }
      void ok1()   {
        System.out.println(i++ + ++i); //4
      }
      void ok2()   {
        System.out.println(++i + i++); // 8
      }
      void ok3()   {
        int i = 1; // local variable
        System.out.println(++i + i++); // 4
      }
      void ok4()   {
        System.out.println(i++ + ++i); // 12
      }
    }
    
ขอบซ้ายขอบบน
Inheritance (review)
4. การใช้งานตัวแปรภายใน class และการสืบทอด father
:: การเรียกใช้ instance จาก father มี 4 แบบ
:: 1. จองพื้นที่ใน heap ทำให้มี memory ของตนเอง
:: 2. ถ้ามีการสืบทอด สามารถเรียกใช้ instance ได้ทันที
:: 3. การเรียกใช้ instance ที่สืบทอดมา อาจมีชื่อ class กำกับหรือไม่ก็ได้ ถ้าไม่ซ้ำ
:: 4. ใน package เดียวกัน เรียกใช้ instance ใน class ต่าง ๆ ได้ง่าย
:: ให้นักศึกษาอธิบายว่าตัวอย่างนี้ตอบข้อ 1 - 4 หรือไม่ อย่างไร
    
    class father {
      int box1 = 5;
      static int box2 = 10;
      static Integer box3 = new Integer(15);
      static Integer box4;
    }
    // ===
    class child extends father {
      public static void main(String args[]) {
        father gift = new father();
        father money = new father();
        gift.box1 = 7;
        System.out.println(gift.box1 + money.box1); // 12
        box2 = 1;
        System.out.println(gift.box1 + money.box2 + box2); // 9    
        System.out.println(father.box2 + box2); // 2
        System.out.println(father.box3 + box3); // 30
        System.out.println(father.box4); // null
      }
    }
    // ===
    class anotherchild {
      public static void main(String args[]) {
        System.out.println(father.box2); // 10
        System.out.println(father.box3); // 15
        System.out.println(father.box4); // null
      }
    }
    
ขอบซ้ายขอบบน
Collection & Array
5. array ธรรมดา แบบ int
:: อ่านค่าเก็บลงอาเรย์ 5 จำนวน แล้วนำมาหาค่า max
:: ตามภาพผังงานใน http://www.thaiall.com/programming
:: slide ของ ผศ.ธนิศา เครือไวศยวรรณ อธิบายเรื่อง collection ได้ละเอียด และชัดเจน
    
    import java.io.*;
    class ar5max {
     public static void main(String args[]) throws IOException {
      BufferedReader stdin;
      stdin=new BufferedReader(new InputStreamReader(System.in));    
      int buf[] = new int[5];
      int i,max=0;
      for (i=0;i<5;i++) {
        buf[i] = Integer.parseInt(stdin.readLine());
      }  
      for (i=0;i<5;i++) {
        if (buf[i] > max) { max = buf[i]; }
      }
      System.out.println("Max = " + max);
     }
    }
    
6. การใช้ Array กับ object ภายนอก
:: Friend คือ คลาสที่มี object และ constructor รับค่าไปเก็บไว้
:: เมื่อเรียกใช้ก็ต้องกำหนด index และจำนวนสมาชิกสามารถใช้ .length
    
    class Friend {
      String name;
      Integer age;
      Friend(String name,Integer age) { 
         this.name = name;
         this.age = age;
      }
    }
    class child {
      public static void main(String args[]) {
        Friend f[] = {
          new Friend("tom",9),new Friend("boy",6),
          new Friend("jack",11),new Friend("jojo",10)
       };
       System.out.println(f[0].name); 
       System.out.println(f[1].name);
       System.out.println(f.length);
      }
    }
    
7. การสร้าง method สำหรับเก็บวัตถุ แล้วเรียกใช้วัตถุภายในคลาสเดียวกัน
:: สร้าง method สำหรับเก็บวัตถุ โดยวัตถุเก็บในอาร์เรย์แบบ Comparable
:: สร้าง method สำหรับนำวัตถุที่เก็บไว้ใน instance ชื่อ ar มาแสดงแบบ fixed
:: โปรแกรมถูกปรับจาก http://www.thaiall.com/class/TestBubbleSort.java
:: ใช้ Value type แบบ Comparable ซึ่งมี compareTo method ให้เรียกใช้ มักใช้เก็บข้อมูลเพื่อการเปรียบเทียบ
:: method ในคลาส Arrays มีให้ใช้ไม่น้อย ที่ http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
    
    class child {
      static int elems=0; 
      static Comparable ar[] = new Comparable[2];
      public static void main(String[] args) {
        insert(new Integer(6));
        insert(new Integer(5));
        java.util.Arrays.sort(ar);
        printresult();
      }
      static void insert(Comparable value) { 
        ar[elems] = value;
        elems++;
      }  
      static void printresult() {
        System.out.println(ar[0]+"|"+ar[1]);  // 1|2
      }
    }
    
8. การสร้าง method สำหรับเก็บวัตถุ แล้วเรียกใช้วัตถุภายในคลาสเดียวกัน
:: Comparable จะรับวัตถุได้หลายประเภท ถ้าต้องการตรวจประเภทวัตถุ ก็ใช้ .getClass()
:: compareTo ใช้สำหรับการเปรียบเทียบวัตถุแบบ Comparable มีผล 3 แบบ
:: วัตถุต่างประเภทกันใช้ compareTo ไม่ได้ และผลการ compile มี warning ของ compareTo
    
    class x {
      static int elems=0; 
      static Comparable ar[] = new Comparable[5];
      public static void main(String[] args) {
        insert(new Integer(1));
        insert(new String("is 2"));
        insert(new Double(1.2));
        insert(new Boolean(true));
        insert(new Integer(2));
        printresult();
      }
      static void insert(Comparable value) { 
        ar[elems++] = value;
      }  
      static void printresult() {
        System.out.println(ar[0]+"|"+ar[1]+"|"+ar[2]+"|"+ar[3]); 
        if(ar[0].compareTo(ar[4]) < 0) 
          System.out.println("less than"); // print
        System.out.println(ar[2].getClass());
        // class java.lang.Double
      }
    }
    
9. การสร้าง 2 class เรียกใช้ method สำหรับจัดการข้อมูลใน ArrayList แบบ Integer ปรับจากตัวอย่างก่อนหน้านี้
:: สร้าง method สำหรับเก็บวัตถุ โดยวัตถุเก็บใน ArrayList แบบ Comparable
:: สร้าง method สำหรับนำวัตถุที่เก็บไว้ใน instance ชื่อ ar มาแสดงแบบ flexible
:: การใช้ ArrayList ต้อง import.util.ArrayList
:: จำนวนใน ArrayList จะใช้ .size() ส่วนการเรียกค่าสมาชิกออกมา จะใช้ .get(i)
    
    import java.util.ArrayList;
    class x {
      public static void main(String[] args) {
        Myclass work = new Myclass();
        work.insert(new Integer(1));
        work.insert(new Integer(2));
        work.printresult();
      }
    }
    class Myclass {
      ArrayList<Integer> ar = new ArrayList<Integer>();
      public void insert(Integer value) { 
        ar.add(value);
      }  
      public void printresult() {
        for(int i=0;i<ar.size();i++) 
         System.out.print(ar.get(i)+"|");  // 1|2|
      }
    }
    
10. การใช้ ArrayList และ Generic
:: instanceof ใช้ตรวจสอบประเภทของวัตถุ
:: การรับข้อมูลจากแป้นพิมพ์แบบ String จะใช้ BufferedReader
:: ถ้ารับข้อมูล 10 ระเบียนจะเขียนอย่างไร และรับจนกว่าจะพิมพ์ว่า end ต้องเขียนอย่างไร
    
    import java.util.ArrayList;
    import java.io.*;
    class x {
      public static void main(String[] args) throws IOException {
        Myclass work = new Myclass();
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        String buf = stdin.readLine();
        work.insert(new Integer(Integer.parseInt(buf)));
        buf = stdin.readLine();
        work.insert(new String(buf));
        buf = stdin.readLine();
        work.insert(new Integer(Integer.parseInt(buf)));
        buf = stdin.readLine();
        work.insert(new String(buf));
        work.printresult();
      }
    }
    class Myclass {
      ArrayList<Integer> id = new ArrayList<Integer>();
      ArrayList<String> name = new ArrayList<String>();
      public void insert(Object value) { 
        if (value instanceof Integer) {
    	id.add((Integer)value);
        } else {
        name.add((String)value);
        }
    
      }  
      public void printresult() {
        for(int i=0;i<id.size();i++) 
         System.out.println(id.get(i)+"|"+name.get(i));  
      }
    }
    
11. การใช้ TreeSet แบบใช้ Iterator และไม่ใช้
:: การวนลูปเข้าใน TreeSet จะได้ object ที่นำมาแสดงผลราย item ได้
:: พบตัวอย่างที่ http://www.java-tips.org/java-se-tips/java.util/how-to-use-treeset.html
    
    import java.util.*;
    public class child {
    public static void main(String args[]) {
      TreeSet t = new TreeSet();
      t.add("B");
      t.add("C");
      t.add("A");
      t.add("D");
      System.out.println(t); //  [A, B, C, D]
      Iterator tn =t.iterator();
      while(tn.hasNext()){
        Object o = tn.next();
        System.out.print(o); // ABCD
      }
    }
    }
    

http://www.c-sharpcorner.com/UploadFile/433c33/vector-class-in-java/
ขอบซ้ายขอบบน
Constructor
12. การเรียกใช้ object แบบมี constructor
:: ถ้าสืบทอดด้วย extends จะไม่ต้องเรียกใช้ constructor
:: ถ้าสืบทอด แต่ยังกำหนด reference อีก ก็ยังต้องผ่าน constructor
:: งานมอบหมาย จงเขียนโปรแกรมที่ใช้ work โดยไม่เรียกใช้ constructor
    
    class friend {
      friend() { 
        System.out.println("ok 1");
      }
      void work() { 
        System.out.println("ok 2");
      }
    }
    class child {
      public static void main(String args[]) {
        friend f = new friend();
        f.work();
      }
    }
    
13. การเรียกใช้ object จากอีก class หนึ่งแบบไม่มี constructor
:: การไม่ประกาศ constructor นั้น ภาษาจาวาจะสร้างให้อัตโนมัติ แต่ไม่มี behavior ใด ๆ
:: การเรียกใช้ method แบบกำหนด reference และไม่กำหนด reference
:: แบบไหนเรียกว่ามี reference และแบบไหนเรียกว่าไม่มี
    
    class Myclass { 
      void showValue() { 
        System.out.println("xx"); 
      } 
    } 
    class x { 
      public static void main(String args[]) { 
        System.out.println("x"); 
        new Myclass().showValue(); 
        Myclass work = new Myclass();  // ไม่มี constructor ใน Myclass
        work.showValue(); 
      } 
    } 
    // Result of this program
    // x
    // xx 
    // xx
    
14. การเรียกใช้ object จากอีก class หนึ่งแบบมี constructor
:: การเรียกใช้ method แบบกำหนด reference และไม่กำหนด reference
:: ถ้ากำหนด reference จะเรียกใช้ constructor เพียงครั้งเดียว ในตอนที่สั่ง new
:: constructor คือ method ที่ไม่มี return type หรือ modifier และไม่สามารถกำหนดเป็น static
    
    class Myclass { 
      static void showValue() { 
        System.out.println("y"); 
      } 
      Myclass() {
        System.out.println("x"); 
      }
    } 
    class x { 
      public static void main(String args[]) { 
        System.out.println("z"); 
        new Myclass().showValue();  
        Myclass a = new Myclass();  
        a.showValue();          
        new Myclass();         
        // Myclass.Myclass();   error
        // showValue(); // ok if have extends Myclass
        Myclass.showValue(); // showValue must be static
      } 
    } 
    // Result of this program
    // zxyxyxy
    
ขอบซ้ายขอบบน
Overload
15. Overload คือ method ชื่อเดียวกัน รับค่าต่างรูปแบบ จะมีพฤติกรรมต่างกัน
:: constructor ก็สามารถทำ Overload ได้
:: Overload จะมี return type แบบเดียวกัน แต่รับค่าต่างรูปแบบกัน
    
    // x.java
    class a {
      int b;
      a() { p("Call object a"); }
      a(int i) { p("Number is " + i); }
      void c() { p("Receive nothing"); }
      void c(int i) { p("Number = " + i); }
      void c(String d) { p("Word = " + d); }
      static void p(String s) { System.out.println(s); }
    }
    class x {
      public static void main(String args[]) {
        a n = new a(2);
        n.c();
        n.c(3);
        n.c("This is test");
        new a();
      }
    }
    // Result of this program
    // Number is 2
    // Receive nothing
    // Number = 3
    // Word = This is test
    // Call object a
    
ขอบซ้ายขอบบน
Inheritance & Override
16. นำ my55.java ที่เคยพัฒนาไว้ กลับมาใช้ใหม่ใน my56.java
:: เขียน my55.java เรียกใช้ showValue
:: ต่อมาก็เขียน my56.java เพื่อเรียกใช้ showValue
:: เมื่อแปล my56.java จะนำแฟ้ม my55.java มาแปล เพื่อให้ได้ my55.class ทุกครั้ง
:: ถ้าเรียกใช้ my55 ก็จะนำ my55.java มาแปล แต่ถ้าไม่พบ my55.java ก็จะเป็น error
    
    // my55.java
    class my55 { 
      public static void main(String args[]) { 
        showValue(); 
      } 
      static void showValue() { 
        System.out.println("egg"); 
      } 
    } 
    
    // my56.java
    class my56 { 
      public static void main(String args[]) { 
        System.out.println("hen"); 
        my55 work = new my55(); 
        work.showValue(); 
      } 
    }
    // Result of my56
    // hen
    // egg
    
17. Inheritance และ Override : การสืบทอดจากรุ่นปู่ไปรุ่นหลาน
:: Override คือ การกำหนดพฤติกรรมใหม่ใน object แต่ไม่เปลี่ยน return type
:: กิจกรรมต่างกันไปในแต่ละรุ่น ตั้งแต่รุ่นปู่ ไปถึงรุ่นหลาน
    // a1.java : รุ่นปู่ กำหนดค่าให้ i แล้วพิมพ์ 2 บรรทัด
    class a1 {   
      static int i;
      public static void main(String args[]) { 
        seti();
        printnumber(i); 
        printline(); 
      } 
      static void seti() { 
        i = 1; 
      } 
      static void printnumber(int j) { 
        System.out.println("Number = " + j); 
      } 
      static void printline() { 
        System.out.println("=========="); 
      } 
    } 
    
    // a2.java : รุ่นพ่อ กำหนดค่า i เอง ไม่ใช้ seti() และไม่พิมพ์เส้น
    public class a2 extends a1 {
      static int i = 2;
      public static void main (String[] args) {
        printnumber(i); 
      }
    }
    
    // a3.java : รุ่นหลาน เปลี่ยนรูปแบบเส้น และไม่ใช้ i จากรุ่นก่อน
    public class a3 extends a2 {
      public static void main(String args[]) { 
        printnumber(3); 
        printline(); 
      } 
      static void printline() { 
        System.out.println("----------"); 
      } 
    }
    
    // a4.java : รุ่นเหลน เปลี่ยน seti ให้เรียก setinew ที่ช่วยกำหนด i ใหม่ 
    public class a4 extends a3 {
      public static void main(String args[]) { 
        seti();
        printnumber(i); 
        printline(); 
      } 
      static void seti() { 
        // override หรือสืบทอดเปลี่ยนได้เฉพาะ code  
        i = setinew(); 
      } 
      static int setinew() {     
        i = 4; 
        return i;
      } 
    }
    
18. Inheritance และ constructor : run constructor ของ superclass ตามด้วย subclass
:: ปกติ default constructor คือ object ที่มีชื่อเดียวกับ class และไม่มีส่วนขยายใด ๆ
:: a.java มี constructor เป็นโปรแกรมที่ compile ผ่าน แต่ run ไม่ได้ ออกแบบให้ถูกเรียกใช้อย่างเดียว
:: b.java มี constructor และทำงานภายใต้ main เรียก constructor ทั้ง 2 มาทำงาน
:: constructor คือ default object จะส่งค่าให้ constructor ก็ได้
:: การแปล b.java จะเรียก a.java มาแปลด้วยถ้าไม่พบ a.class แต่ถ้าพบ และ a.java ไม่เปลี่ยน ก็จะไม่แปล a.java ใหม่
:: constructor ของ a ถูกเรียกใช้ตอน new b() และจะทำงานก่อน constructor ของ b ตามหลัก inheritance
    
    // a.java 
    public class a {
      a() {
        System.out.println("a constructor");
      }
    }
    
    // b.java
    public class b extends a {
      b(int i) {
        System.out.println("b constructor " + i);
      }
      public static void main (String[] args) {
        b xxx = new b(100);
      }
    }
    // Result of this program
    // a constructor
    // b constructor 100
    
19. การทำงานของ superclass และ subclass ใน inheritance
:: a.java เป็น superclass เพราะมี b.java เรียกไปใช้
:: b.java เป็นทั้ง superclass และ subclass เพราะเป็นทั้งลูก และพ่อ
:: c.java เป็นทั้ง subclass อย่างเดียว
:: การใช้ c d = new c(); จะเรียก constructor ของปู่ ตามด้วยพ่อ และลูกมาทำงาน แต่ไม่เรียก main
:: super.aa() ใช้เรียก aa() จาก superclass มาทำงาน
:: แม้มีหลายชั่วคน คำสั่ง new a().aa(); ก็ไม่ผ่านแต่ละรุ่น เพราะเรียกตรงไม่ผ่าน inheritance
:: ถ้ามีคำว่า public หน้าชื่อคลาส จะต้องแยกแต่ละ class เป็นแต่ละ .java ถ้าไม่มีก็ compile ครั้งเดียวได้
    
    // a.java is superclass
    public class a {
      a() {
        System.out.println("a constructor");
      }
      void aa() {
        System.out.println("aa in class a");
      }
    }
    
    // b.java is superclass of c.java and subclass of a.java
    public class b extends a {
      b() {
        System.out.println("b constructor");
      }
      void aa() {
        System.out.println("aa in class b");
      }
    }
    
    // c.java is subclass of b.java
    public class c extends b {
      c() {
        System.out.println("c constructor ");
      }
      void aa() {
        System.out.println("aa in class c");
        super.aa(); // call aa in superclass
        new a().aa();
      }
      public static void main(String args[]) { 
        c d = new c();
        d.aa();
        // aa(); can not run because aa should be static
        new a().aa();
      } 
    }
    // Result of this program
    // a constructor
    // b constructor
    // c constructor
    // aa in class c
    // aa in class b
    // a constructor
    // aa in class a
    // a constructor
    // aa in class a
    
ขอบซ้ายขอบบน
Composition
20. Composition : แบบ constructor initialization with composition
:: โปรแกรมจะสร้างวัตถุทันที 2 กรณีคือ เมื่อจองพื้นที่ใน heap และคลาส b ถูกเรียก
:: โดย aa จองพื้นที่สำหรับ a() เมื่อมีการสร้าง reference x ขึ้นมา
:: วัตถุ aa จะจองพื้นที่ใน heap ต่อเมื่อสั่ง b x = new b()
:: วัตถุ bb จะจองพื้นที่ใน heap ต่อเมื่อมีการเรียกคลาส b ขึ้นมา ในครั้งแรก
:: ถ้าใน main ว่างเปล่า aa ก็จะไม่จองพื้นที่ใน heap แต่ bb จะจองพื้นที่ครั้งแรกครั้งเดียว
:: ถ้าเพิ่ม public a cc = new a(); ก็จะทำงานในเงื่อนไขเดียวกับ aa
:: Composition คือ การนำ class มาประกอบกัน อย่างตรงไปตรงมา ไม่เหมือนกับ Inheritance ที่ความสำคัญของคลาสเป็นลำดับชั้น
    
    // a.java
    public class a {
      a() {
        System.out.println("a constructor");
      }
    }
    
    // b.java
    public class b {
      public a aa =  new a(); 
      static a bb =  new a();
      public static void main (String args[]) {
        b x = new b();
      }
      b() {
        System.out.println("b constructor");
      }
    }
    // Result of this program
    // a constructor
    // a constructor
    // b constructor
    
21. Composition : แบบ delayed initialization
:: โปรแกรมจะนิยามวัตถุ แต่ยังไม่สร้าง จนกว่าจะใช้งานจึงขอพื้นที่ใน heap
:: วัตถุ a ถูกสร้างภายหลัง หลังจากเข้า main และใช้ x จองพื้นที่ให้ b() กรณีนี้สร้าง a 2 แบบ
:: ใน constructor สามารถเรียก method ที่ไม่เป็น static จากใน main ได้
:: ถ้าใน main เรียก aa โดยตรง ซึ่ง aa ไม่เป็น static จะพบ error ตอน compile
:: http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ308.htm
    
    // a.java
    public class a {
      a() {
        System.out.println("a constructor");
      }
    }
    
    // b.java
    public class b {
      public a aa; 
      public static void main (String args[]) {
        b x = new b();
        if(x.aa == null) x.aa = new a();
        // if(aa == null) aa = new a(); // static of aa required
      }
      b() {
        System.out.println("b constructor");
        new a();
      }
    }
    // Result of this program
    // b constructor
    // a constructor
    // a constructor
    
22. Composition : การนำ class มาประกอบกัน
:: มี car.java เรียก wheel.java และ door.java มาประกอบเข้าด้วยกัน โดยไม่ใช้การสืบทอด
:: thecar ใน wheel.java และ door.java ถูกสร้างเป็น reference แต่ไม่ถูกใช้ จะไม่มีก็ได้
:: แต่ถ้ามี thecar ก็ต้องมีแฟ้ม car.java หรือ car.class มิเช่นนั้นแปลไม่ผ่าน
:: หากไม่มี public หน้า class ใดเลย จะรวมทั้งหมดใน .java เดียวได้ แต่ถ้ามี public ทุกคลาสก็ต้องแฟ้มละคลาส
    // เมื่อแปล wheel จะแปล car ด้วย
    // wheel.java
    public class wheel {
      private int a;
      private int b;
      public car thecar;
      wheel() {
        System.out.println("constructor wheel() from class wheel");
      }
      public void putwheel() {
        System.out.println("putwheel() from class wheel");
      }
    }
    
    // เมื่อแปล door จะแปล car ด้วย
    // door.java
    public class door {
      private int x;
      private int y;
      public car thecar;
      door() {
        System.out.println("constructor door() from class door");
      }
      public void putdoor() {
        System.out.println("cleandoor() from class door");
      }
    }
    
    // แปล car จะแปล และได้ wheel.class และ door.class
    // car.java
    public class car {
      public wheel thewheel =  new wheel();
      public door thedoor =  new door();
      public static void main (String args[]) {
        car  x = new car();
        x.thewheel.putwheel();
        x.thedoor.putdoor();
      }
      car() {
        System.out.println("Constructor car()");
      }
      public void drive() {
        System.out.println("drive()");
      }
    }
    // Result of this program
    // constructor wheel() from class wheel
    // constructor door() from class door
    // Constructor car()
    // putwheel() from class wheel
    // cleandoor() from class door
    
ขอบซ้ายขอบบน
Package
23. program in package
:: เติมบรรทัดแรก เพื่อระบุว่า โปรแกรมนี้อยู่ใน package ชื่อ burin
:: protected ถูกกำหนดหน้า myhome เพื่อระบุว่านอก method มาเรียกใช้ไม่ได้
:: หลัง compile ผมจะ copy ไปไว้ในห้อง /bin/burin ในกรณี source อยู่ใน /bin
:: ถ้า source อยู่ใน /bin/burin ก็ compile แล้ว run ด้วย javac burin/x.java ก็ได้
:: ประมวลผลด้วย DOS>java burin/x
    
    package burin; 
    public class x { 
      public static void main (String args[]) { 
        System.out.println("NTU"); 
        myhome();
      } 
      protected static void myhome() { 
        System.out.println("University"); 
      } 
    } 
    
24. call package
:: ถ้าอยู่ใน package เดียวก็เรียกใช้กันได้ปกติ แม้มี method ที่กำหนด protected ไว้
:: คลาสหนึ่งจะอยู่หลาย package ไม่ได้ แต่เรียกโปรแกรมจากหลาย package มาใช้ได้
:: ใน package สืบทอดกันได้ปกติตามหลัก inheritance
:: ถ้าเรียกใช้ class ใน package จากข้างนอก ต้องกำหนด class เป็น public
:: method ใน package ที่จะถูกเรียกจากข้างนอก ต้องกำหนด public จะเป็น default ไม่ได้
    
    package burin;
    class y { 
      public static void main (String[] args) { 
         x a = new x();
         a.myhome();
      } 
    }
    // ===
    package burin;
    public class y extends x {  } 
    
25. call package from outside
:: คำว่า import ใช้เรียก package และมีหลายบรรทัดได้
:: ถ้าอยู่นอก package ให้ใช้ import
:: โปรแกรมนี้เรียก myhome ที่กำหนดเป็น protected ไม่ได้ ต้องแก้ไขเป็น public ทั้ง class และ method
    
    import burin.*;
    class z { 
      public static void main (String[] args) { 
         x a = new x();
         a.myhome();
      } 
    } 
    
26. package หมายถึง subdirectory หรือ library ที่เก็บ class ไว้ใช้งาน
ในอนาคต หากมี .class หลายร้อยแฟ้ม และเก็บแยก directory อย่างเป็นระเบียบ เช่น ห้อง c:\java\bin\aaa เก็บ .class 100 แฟ้ม และ c:\java\bin\burin เก็บ . class 150 แฟ้ม การเรียกใช้จากแต่ละห้อง สามารถทำได้ด้วยการใช้คำสั่ง import แต่ class ที่อยู่ในแต่ละห้องจะประกาศด้วยคำสั่ง package และมีข้อมูลว่าแต่ละห้อง จะต้องมีชื่อ class ที่ไม่ซ้ำกัน
ตัวอย่างนี้ สร้าง class ของ burin ขึ้น 2 class คือ yonok1.java และ yonok2.java โปรแกรมที่ใช้เรียก package คือ testpackage.java โปรแกรม testpackage.java จะ compile ผ่าน จำเป็นต้องมีห้อง c:\java\bin\burin และในห้อง burin ต้องมีแฟ้มชื่อ yonok1.class และ yonok2.class ไว้แล้ว
    
    // yonok1.java 
    package burin; 
    public class yonok1 { 
      public yonok1() { 
        System.out.println("YONOK"); 
      } 
    } 
    
    // yonok2.java 
    package burin; 
    public class yonok2 { 
      public yonok2() { 
        System.out.println("Burin Rujjanapan"); 
      } 
      public void prt(String s){ 
        System.out.println(s); 
      } 
    } 
    
    // import testpackage.java 
    import burin.*; 
    class testpackage { 
      public static void main (String[] args) { 
        yonok1 xxx = new yonok1(); 
        yonok2 yyy = new yonok2(); 
        yyy.prt("test of package"); 
      } 
    } 
    // Result of this program
    // YONOK 
    // Burin Rujjanapan 
    // test of package
    
ขอบซ้ายขอบบน
try .. catch ..
27. ความผิดพลาดมี 2 แบบ (Type of errors)
Java ถือว่าความผิดปกติ คือ วัตถุชนิดหนึ่งที่บรรจุรายละเอียดของความผิดปกติที่เกิดขึ้น ณ สภาวะแวดล้อมนั้น ๆ
  1. Compile-time errors : เป็นความผิดพลาดที่จะแสดงจุดผิดพลาดให้เห็นขณะสั่งแปล
  2. Run-time errors
    1. ความผิดพลาดในวิธีคิด (Program logic)
    2. ความผิดพลาดจากสภาวะแวดล้อมไม่สมประกอบ (Status environment)
    
    class x {
      public static void main(String args[]  {
        System.out.println("aa");
      }
    }
    or
    class x {  
      public static void main(String args[]) {
        for(int j=5;j>-5; j--) {
          System.out.println(5/j); // เกิด arithmetic error ขณะ run-time
        }
      }
    }
    
28. try และ catch จับความผิดปกติ เมื่อพบแล้วหยุด
:: ข้อมูล exception จาก http://klomp.org/mark/classpath/doc/api/html/java/lang/classes.html
เช่น ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException ClassNotFoundException CloneNotSupportedException Exception IllegalAccessException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException InstantiationException InterruptedException NegativeArraySizeException NoSuchFieldException NoSuchMethodException NullPointerException NumberFormatException RuntimeException SecurityException StringIndexOutOfBoundsException UnsupportedOperationException
    
    class x {  
      public static void main(String args[]) {
        System.out.println("===== start =====");
        try {
          for(int j=5;j>-5; j--) {
            System.out.println(7/j);
          }
        } catch (ArithmeticException e) {
            System.out.println("You divide by zero");      
        }
        System.out.println("===== finish =====");
      }
    }
    // Result of this program
    // ===== start =====
    // 1
    // 1
    // 2
    // 3
    // 7
    // You divide by zero
    // ===== finish =====
    
29. try และ catch จับความผิดปกติ ไม่หยุดเมื่อพบข้อผิดพลาด
    
    class x {  
      public static void main(String args[]) {
        System.out.println("===== start =====");
        for(int j=2;j>-2; j--) {
          try {
            System.out.println(7/j);
          } catch (ArithmeticException e) {
            System.out.println("You divide by zero");      
          } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error on array");      
    	  } finally {
             System.out.println("Each case");      
          }
        }
        System.out.println("===== finish =====");
      }
    }
    // Result of this program
    // ===== start =====
    // 3
    Each case
    // 7
    Each case
    // You divide by zero
    Each case
    // -7
    Each case
    // ===== finish =====
    
"Imagination is more important than knowledge" - Albert Einstein
Home
Thaiabc.com
Thainame.net
Lampang.net
Nation university
PHP
MySQL
Visual basic.NET
TabletPC
Linux
Online quiz
Download
Search engine
Web ranking
Add website
Blog : Education
Blog : ACLA
Blog : Lampang
Facebook.com
Twitter.com
About us
My dream
Site map
Sponsor
http://goo.gl/72BPC