ตัวอย่างโปรแกรม แสดง การโปรแกรมเชิงวัตถุ

ปรับปรุง : 2551-08-22 (ปรับเนื้อหา)
    รวมตัวอย่างที่เน้นการโปรแกรมแบบ OOP
  1. Object แรกของ class มักชื่อ main โปรแกรมนี้สั้น และง่ายที่สุด
    :: สร้างกล่อง 1 กล่องในกล่องมี object ทำงาน พิมพ์ x เพียงอักษรเดียว
    :: ถ้าผมมองว่า class ก็คือกล่อง แต่ละกล่องคือที่เก็บ object
  2. เรียก object ใน class เดียวกัน โดยมองว่า class เสมือนกล่องเก็บ object มากมาย
    :: สร้างกล่อง 1 กล่องในกล่องมี 2 object และ object 1 เรียก object 2 มาทำงาน
  3. เรียก object จากต่าง class หรือใน class เดียวกัน
    :: ลดรูปมาจากโปรแกรม TestBubbleSort.java
    :: ใช้ Value type แบบ Comparable
  4. เรียก object จากอีก class หนึ่งในแฟ้ม x.java เดียวกัน แต่ไม่มี constructor
    :: มี 2 กล่อง ให้เรียก object จากอีกกล่องมาทำงาน แสดงวิธีเรียก 2 วิธี
  5. เรียก object จากอีก class ถ้าใน class นั้นมี constructor ๆ ก็จะทำงานก่อน object
    :: คล้ายตัวอย่างข้างต้น แต่เพิ่ม default object เข้าไปใน class xxx
    :: ทุกครั้งที่เรียก object ใดใน class xxx ตัว default object ก็จะทำงานด้วย
  6. นำ x.java ที่เคยพัฒนาไว้ กลับมาใช้ใหม่โดย y.java
    :: เริ่มเขียน x.java ก็ใช้งานได้ปกติ มี object subx ไว้ใช้งาน
    :: ต่อมาอีก 5 ปี ต้องการใช้ object subx อีก ไม่ต้องการเขียนใหม่ จึงเรียกใช้ subx จาก x.class
    :: เมื่อแปล y.java หากไม่พบ x.class จะนำ x.java มาแปลจนได้ x.class เพื่อเรียกใช้
  7. Overloading : มี 1 class แต่ object เดียวกัน มีพฤติกรรมต่างกัน ตามวิธีการเรียกใช้
    :: Class เดียวกัน ชื่อ object เหมือนกัน แต่เลือกกระทำได้แตกต่างกัน
    :: ความแตกต่างถูกแยกด้วยวิธีการเรียกใช้ โดยพิจารณาจากค่า หรือข่าวสารที่ส่งเข้าไป
  8. Inheritance และ override : การสืบทอดจากรุ่นปู่ไปรุ่นหลาน
    :: Override คือ เปลี่ยนกิจกรรมใน object แต่ไม่สามารถเปลี่ยน return type
    :: กิจกรรมต่างกันไปในแต่ละรุ่น ตั้งแต่รุ่นปู่ ไปถึงรุ่นหลาน
  9. 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 ใหม่
  10. Inheritance และ superclass,subclass : แสดงการทำงานของ superclass และ subclass
    :: a.java เป็น superclass เพราะมี b.java เรียกไปใช้
    :: b.java เป็นทั้ง superclass และ subclass เพราะเป็นทั้งลูก และพ่อ
    :: การใช้ c d = new c(); จะเรียก constructor มาทำงาน แต่ไม่เรียก main
    :: หากมีลำดับชั้นหลายชั้น คำสั่ง new a().aa(); สามารถเรียกโดยไม่สนใจลำดับชั้นเดิม
    :: super.aa() ใช้เรียก aa() จาก superclass มาทำงาน
  11. Composition : การนำ class มาประกอบกัน อย่างตรงไปตรงมา
    :: โปรแกรมจะสร้างวัตถุทันทีเมื่อ run b.class
    :: แต่วัตถุที่สร้างขึ้นยังไม่ทำงาน จะทำงานเมื่อ b x = new b()
  12. Composition : แบบ delayed initialization
    :: โปรแกรมจะนิยามวัตถุ แต่ยังไม่สร้าง จนกว่าจะใช้งาน
    :: วัตถุ a ถูกสร้างภายหลัง หลังจากเข้าส่วน main ไปแล้ว
  13. Composition : การนำ class มาประกอบกัน
    :: มี car.java เรียก wheel.java และ door.java มาประกอบเข้าด้วยกัน โดยไม่ใช้การสืบทอด
  14. Upcasting ใน การพ้องรูป(Polymorphism)
    ตัวอย่างนี้ แสดงให้เห็นว่าหลักการของ Upcasting สามารถเรียก constructor ของ class แม่มาทำงาน เมื่อมีการสร้าง object ลูกได้ ด้วยคำสั่ง a xxx1 = new a1(); เพื่อ a1 เป็น class ลูกของ a ต่อไปเมื่อสั่งงาน xxx1.anymethod(); ก็จะควานหาจากใน a1 มิใช่ a นะครับ
      // x.java : เรียก a1 ซึ่งเป็นลูกของ a มาทำงาน 
      class a { 
        a() { 
          System.out.println("a"); 
        } 
        static void a22() { 
          System.out.println("oh no"); 
        } 
      } 
      class a1 extends a { 
        a1() { 
          System.out.println("a1"); 
        } 
      } 
      class a2 extends a { 
        a2() { 
          System.out.println("a2"); 
        } 
        static void a22() { 
          System.out.println("a22"); 
        } 
      } 
      public class x { 
        public static void main (String args[]) { 
          a xxx1 = new a1(); 
          a xxx2; 
          xxx2 = new a2(); 
          a2 xxx3 = new a2(); 
          xxx3.a22(); 
        } 
      } 
      // Result of this program 
      // a 
      // a1 
      // a 
      // a2 
      // a 
      // a2 
      // a22
      
  15. สร้างปุ่ม Exit เพื่อปิด appletviewer ซึ่งทำงานด้วย awt ทำงานใน applet viewer
      import java.awt.*; 
      import java.awt.event.*; 
      public class x implements ActionListener { 
        Frame s = new Frame("Screen"); 
        Button bclose = new Button("Exit"); 
        public static void main(String[] args) { 
          new x().init(); 
        } 
        public void init( ) { 
          s.setSize(150,150); 
          s.setLayout(null);    // ถ้าไม่มี setLayout หรือ setVisible 
          s.setVisible(true);   // จะกลายเป็นปุ่มเต็มจอ
          s.setBackground(Color.yellow); 
          bclose.setBounds(10,40,70,20); 
          s.add(bclose); 
          bclose.addActionListener(this); 
          s.show(); 
        } 
        public void actionPerformed(ActionEvent a) { 
          if(a.getSource()==bclose) { System.exit(0); } 
        } 
      }
      
      // การ compile และ run ก็ใช้ javac และ java ตามปกติ แต่โปรแกรมจะเรียก appletviewer มาทำงานเอง
      // คำสั่ง System.exit(0) หมายถึง Stops Java Virtual Machine (JVM)


  16. สร้างปุ่มเพิ่มเลขทีละ 5 และปุ่ม exit ด้วย awt ทำงานใน applet viewer
      import java.awt.*; 
      import java.awt.event.*; 
      public class x implements ActionListener { 
        Frame s = new Frame("Screen"); 
        Button bclose = new Button("Exit"); 
        Button badd = new Button("Add"); 
        TextField txt = new TextField(10); 
        public static void main(String[] args) { 
          new x().init(); 
        } 
        public void init( ) { 
          s.setSize(150,150); 
          s.setLayout(null); 
          s.setVisible(true); 
          s.setBackground(Color.yellow); 
          txt.setBounds(10,40,70,20); 
          badd.setBounds(10,70,70,20); 
          bclose.setBounds(10,100,70,20); 
          s.add(txt); 
          s.add(badd); 
          s.add(bclose); 
          badd.addActionListener(this); 
          bclose.addActionListener(this); 
          txt.setText("0"); 
          s.show(); 
        } 
        public void actionPerformed(ActionEvent a) { 
          String aa = Double.toString(Double.parseDouble(txt.getText()) + 5); 
          // String aa = Integer.toString(Integer.parseInt(txt.getText()) + 5); 
          if(a.getSource()==badd) { txt.setText(aa); } 
          if(a.getSource()==bclose) { System.exit(0); } 
        } 
      }
      
  17. สร้างปุ่มเรียก frame ใหม่
      import java.awt.*; 
      import java.awt.event.*; 
      public class x implements ActionListener { 
        Frame s1 = new Frame("Screen1"); 
        Frame s2 = new Frame("Screen2"); 
        Button bclose = new Button("Exit"); 
        Button bshow2 = new Button("show2"); 
        public static void main(String[] args) { 
          new x().init(); 
        } 
        public void init( ) { 
          s1.setSize(150,150); 
          s1.setLayout(null); 
          s1.setBackground(Color.yellow); 
          s2.setSize(150,150); 
          s2.setLayout(null); 
          s2.setBackground(Color.green); 
          bshow2.setBounds(10,70,70,20); 
          bclose.setBounds(10,100,70,20); 
          s1.add(bshow2); 
          s1.add(bclose); 
          bshow2.addActionListener(this); 
          bclose.addActionListener(this); 
          s1.setVisible(true);
          // s1.show(); 
        } 
        public void actionPerformed(ActionEvent a) { 
          if(a.getSource()==bshow2) { 
             s1.setVisible(false); 
             s2.add(bclose); 
             bclose.addActionListener(this); 
             s2.show(); 
          } 
          if(a.getSource()==bclose) System.exit(0);
        } 
      }
      
  18. 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
      
  19. abstract class หมายถึง class ที่ไม่ระบุรายละเอียดการทำงาน
    abstract class มีขึ้นเพื่อ class หรือ method ขึ้นมา แต่ยังไม่ระบุการทำงาน การทำงานจะรอให้ class ลูก overriding ระบุการทำงานในภายหลัง
    ถ้าใน class มี method ที่เป็น abstract ตัว class ต้องเป็น abstract class ด้วย หลักการของ abstract ทำให้ลดความซ้ำซ้อนของโปรแกรม และเห็นหน้าที่ของแต่ละ method ได้ชัดเจน แยกหน้าที่การเป็น interface หรือ implementation ได้ชัดเจน
    เมื่อประกาศ workinfile ให้มีการทำงาน 2 method ที่เป็น abstract เมื่อ w รับการสืบทอดไป จะต้องเขียนรายละเอียดการทำงานให้ครบ ในทุก method ที่เป็น abstract มิเช่นนั้น class ที่รับการสืบทอด จำเป็นต้องเป็น abstract ด้วย และถ้า class เป็น abstract ก็จะไม่สามารถ new หรือสร้างวัตถเพื่อทำงานได้
      // x.java
      abstract class workinfile { 
        public abstract void edit(); 
        public abstract void show(); 
        public void display(){ 
          System.out.println("display"); 
        } 
      } 
      class w extends workinfile { 
        public void edit(){ 
          System.out.println("edit"); 
        } 
        public void show(){ 
          System.out.println("show"); 
        } 
      } 
      public class x { 
        public static void main (String args[]) { 
          w aaa = new w(); 
          aaa.edit(); 
          aaa.show(); 
          aaa.display(); 
        } 
      } 
      // Result of this program
      // edit 
      // show
      // display
      
  20. interface หมายถึง abstract class ที่มีทุก method เป็น abstract object
    การเป็น interface class หมายถึงเป็น class ที่เตรียมไว้ให้ class อื่น ๆ เข้ามาติดต่อ โดยปกติการสืบทอดจะใช้ extends แต่ class แบบ interface จะใช้คำว่า implements แทน
      interface a {
        int bb = 10;
        public void show();
        public int i();
      }
      class c implements a {
        public void show() {
          System.out.println("show"); 
        }
        public int i() { return (bb + 5); }
      }
      public class x { 
        public static void main (String args[]) { 
          c aaa = new c(); 
          aaa.show(); 
          System.out.println(aaa.i()); 
        } 
      } 
      // Result of this program
      // show
      // 15
      
  21. package + abstact + interface
      package a;
      public class b{
      
      public void b1() {
      System.out.println("1");
      } } abstract class d{
      void e () {
      System.out.println("2");
      }
      abstract void f (); } interface g{
      int h = 5;
      public void i (); } interface j{
      void k (); } import a.*; public class l extends d implements g,j{
      public static void main(String a[]){
      new b().b1();
      l x = new l();
      x.e();
      x.f();
      x.i();
      x.k();
      System.out.println(x.h);
      }
      public void f () {System.out.println("f");}
      public void i () {System.out.println("i");}
      public void k () {System.out.println("k");} }
  22. ความผิดพลาดมี 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
          }
        }
      }
      
  23. 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 =====
      
  24. 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 =====
      

  25. สืบทอดคุณสมบัติจากตัวแปรใน class
      class y {
        int z = 5;
      }
      class x {
        public static void main(String args[])   {
        // y a = new y();
      	y a,b; 
      	a.z = 1;
          System.out.println(a.z + b.z); // 6
        }
      }
      
  26. การใช้งานตัวแปรภายใน class และการสืบทอด x.java
      class y {
        int z1 = 5;
        static int z2 = 4;
      }
      class x extends y{
        public static void main(String args[]) {
          y a1 = new y();
          y a2 = new y();
          a1.z1 = 3;
          System.out.println(a1.z1 + a2.z1); // 8
          z2 = 1;
          System.out.println(a1.z2 + a2.z2 + z2); // 3
        }
      }
      
  27. การเรียก .class มาใช้ใน .htm แบบ applet
      <applet code="j11.class" width=100 height=100>
      </applet>
      

  28. อ่านค่าเก็บลงอาเรย์ 5 จำนวน แล้วนำมาหาค่า max
    ใช้ภาพผังงานจาก http://www.thaiall.com/programming
      import java.io.*;
      class ar5max {
        public static void main(String args[]) throws IOException {
          BufferedReader 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);
        }
      }
      
  29. Runtime Class และ method #1
      import java.lang.*;
      class x{
        public static void main(String args[]) {
      	Runtime r = Runtime.getRuntime(); 
      	System.out.println("Total memory is: " + r.totalMemory()); 
      	System.out.println("1 Free memory: " + r.freeMemory()); 
      	r.gc(); 
      	System.out.println("2 Free memory: " + r.freeMemory()); 
      	Integer someints[] = new Integer[10]; 
      	System.out.println("3 Free memory: " + r.freeMemory()); 
      	for(int i=0; i<10; i++) {
      	  someints[i] = new Integer(i); // allocate integers 
      	}
      	System.out.println("4 Free memory: " + r.freeMemory()); 
      	for(int i=0; i<10; i++) someints[i] = null; 
      	System.out.println("5 Free memory: " + r.freeMemory());
      	r.gc();  
      	System.out.println("6 Free memory: " + r.freeMemory());
        }
      }
      // Total memory is: 2031616
      // 1 Free memory: 1916848 (- 114768)
      // 2 Free memory: 1946920 (+ 30072)
      // 3 Free memory: 1946304 (- 616)
      // 4 Free memory: 1945872 (- 432)
      // 5 Free memory: 1945600 (- 272)
      // 6 Free memory: 1946864 (+ 1264)
      
  30. Runtime Class และ method #2
      import java.lang.*;
      class x{
        public static void main(String args[]) {
      	Runtime r = Runtime.getRuntime(); 
      	long mem1, mem2; 
      	Integer someints[] = new Integer[1000]; 
      	System.out.println("Total memory is: " + r.totalMemory()); 
      	mem1 = r.freeMemory(); 
      	System.out.println("Initial free memory: " + mem1); 
      	r.gc(); 
      	mem1 = r.freeMemory(); 
      	System.out.println("Free memory after garbage collection: " + mem1); 
      	for(int i=0; i<1000; i++) {
      	  someints[i] = new Integer(i); // allocate integers 
      	}
      	mem2 = r.freeMemory(); 
      	System.out.println("Free memory after allocation: " + mem2); 
      	System.out.println("Memory used by allocation: " + (mem1-mem2)); 
      	// discard Integers 
      	for(int i=0; i<1000; i++) someints[i] = null; 
      	r.gc(); // request garbage collection 
      	mem2 = r.freeMemory(); 
      	System.out.println("Free memory after collecting & discarded Integers: " + mem2);
        }
      }
      // http://www.java-samples.com/showtutorial.php?tutorialid=231
      

แนะนำเว็บใหม่ : ผลการจัดอันดับ
รักลำปาง : thcity.com : korattown.com : topsiam.com : มหาวิทยาลัยโยนก
ศูนย์สอบ : รวมบทความ : ไอทีในชีวิตประจำวัน : ดาวน์โหลด : yourname@thaiall.com
ติดต่อ ทีมงาน ชาวลำปาง มีฝันเพื่อการศึกษา Tel.08-1992-7223