บทนำ: ทำไมต้อง Structure?
เมื่อเขียนโปรแกรม Java แม้จะเป็นโปรแกรมเล็กๆ ก็ต้องเข้าใจ โครงสร้างพื้นฐาน ของมัน เพราะโปรแกรม Java ไม่ได้เขียนแบบสุ่มสี่สุ่มห้า แต่ต้องปฏิบัติตามกฎของ Object-Oriented Programming
โครงสร้างนี้ช่วยให้:
- โปรแกรมเป็นระเบียบและง่ายต่อการอ่าน
- ทำงานร่วมกับคนอื่นได้
- ขยายและปรับปรุงโปรแกรมได้ในอนาคต
- ลดการสับสนเมื่อโปรแกรมใหญ่ขึ้น
- บทนำ: ทำไมต้อง Structure?
- Class: แบบพิมพ์เขียวของ Object
- Class คืออะไร?
- โครงสร้างพื้นฐานของ Class
- Attributes: ข้อมูลของ Object
- Constructor: การสร้าง Object
- Methods: พฤติกรรมของ Object
- Main Method: จุดเริ่มต้นของโปรแกรม
- Main คืออะไร?
- โครงสร้าง Main Method
- ตัวอย่างการใช้ Main Method
- Package: ระบบจัดสรรโค้ด
- Package คืออะไร?
- การสร้างและใช้ Package
- ชื่อ Package: Naming Convention
- Import Statement
- ความสัมพันธ์ระหว่างส่วนประกอบ
- โครงสร้างทั้งหมด
- ตัวอย่างไฟล์ Java ที่สมบูรณ์
- เปรียบเทียบ: Java Structure vs C Structure
- C Structure
- Java Structure
- สรุป: Structure ของโปรแกรม Java
Class: แบบพิมพ์เขียวของ Object
Class คืออะไร?
Class คือ แบบพิมพ์เขียว (Blueprint) สำหรับสร้าง Objects ในโปรแกรม Java
ถ้า Object คือ สิ่งของจริง แล้ว Class คือ แบบแปลน ที่บอกว่าสิ่งของนั้นควรมี อะไรบ้าง (Attributes) และ ทำอะไรได้บ้าง (Methods)
ตัวอย่างในชีวิตจริง:
textClass: Vehicle
├─ Attributes:
│ ├─ brand
│ ├─ color
│ ├─ speed
│ └─ fuelLevel
└─ Methods:
├─ start()
├─ accelerate()
├─ brake()
└─ displayInfo()
Objects จาก Class Vehicle:
├─ Object 1: Car (โตโยต้า, สีขาว, ความเร็ว 0, เชื้อเพลิง 100%)
├─ Object 2: Motorcycle (ฮอนดา, สีแดง, ความเร็ว 0, เชื้อเพลิง 80%)
└─ Object 3: Truck (ม.ค., สีเขียว, ความเร็ว 0, เชื้อเพลิง 60%)
โครงสร้างพื้นฐานของ Class
javapublic class Student {
// 1. ATTRIBUTES (คุณสมบัติ) - ข้อมูล
private String id;
private String name;
private double gpa;
// 2. CONSTRUCTOR (สร้างตัวอักษร) - เตรียมข้อมูลเมื่อสร้าง object
public Student(String id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}
// 3. METHODS (พฤติกรรม) - สิ่งที่ object ทำได้
public void displayInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("GPA: " + gpa);
}
public boolean isGoodStudent() {
return gpa >= 3.5;
}
public void updateGPA(double newGPA) {
this.gpa = newGPA;
}
}
Attributes: ข้อมูลของ Object
Attributes (หรือ Fields, Properties) คือ ตัวแปรที่เก็บข้อมูล ของ object
javapublic class Car {
// Attributes
private String brand; // ยี่ห้อรถ
private String color; // สีรถ
private int year; // ปีผลิต
private double price; // ราคา
private int mileage; // ระยะวิ่ง
private boolean isRunning; // ว่าเครื่องยนต์ทำงานอยู่ไหม
}
Access Modifier (ระดับการเข้าถึง):
private– เข้าถึงได้เฉพาะภายใน class นี้เท่านั้น (ปลอดภัยที่สุด)public– ทุกคนเข้าถึงได้protected– เข้าถึงได้ในแพ็คเกจเดียวกัน และ subclass- default (ไม่ระบุ) – เข้าถึงได้ในแพ็คเกจเดียวกัน
ตัวอย่างการใช้ Attributes:
javapublic class Student {
private String id; // private - ปกป้องข้อมูล
private String name;
private double gpa;
}
public class StudentDemo {
public static void main(String[] args) {
Student student = new Student("6501001", "John", 3.75);
// ✓ ต่อมา (เมื่อเรียน Encapsulation) จะใช้ getter/setter
// System.out.println(student.getName());
// ✗ ไม่สามารถเข้าถึงโดยตรง (private)
// System.out.println(student.name); // ERROR!
}
}
Constructor: การสร้าง Object
Constructor คือ method พิเศษ ที่ทำงาน อัตโนมัติ เมื่อสร้าง object ใหม่ ใช้สำหรับ กำหนดค่าเริ่มต้น (Initialize)
ชื่อ Constructor ต้องเหมือนชื่อ Class และไม่มี return type:
javapublic class Student {
private String id;
private String name;
private double gpa;
// Constructor 1: ต้องส่ง 3 parameter
public Student(String id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
System.out.println("Student created: " + name);
}
// Constructor 2: ไม่ต้องส่ง parameter (Default Constructor)
public Student() {
this.id = "000000";
this.name = "Unknown";
this.gpa = 0.0;
System.out.println("Empty student created");
}
}
ตัวอย่างการใช้ Constructor:
javapublic class StudentDemo {
public static void main(String[] args) {
// เรียก Constructor 1
Student student1 = new Student("6501001", "John", 3.75);
// Output: Student created: John
// เรียก Constructor 2
Student student2 = new Student();
// Output: Empty student created
}
}
ว่า this คืออะไร?
this หมายถึง object ปัจจุบัน ใช้เพื่อ ปรับแยกความเสี่ยง ระหว่าง parameter กับ attribute
javapublic Student(String id, String name, double gpa) {
this.id = id; // this.id = attribute ของ object
// id = parameter ที่รับเข้ามา
this.name = name;
this.gpa = gpa;
}
Methods: พฤติกรรมของ Object
Methods คือ ฟังก์ชัน ที่อยู่ภายใน class ใช้สำหรับ ทำงานบางอย่าง หรือ แสดงพฤติกรรม ของ object
โครงสร้าง Method:
java[access modifier] [return type] [method name]([parameters]) {
// method body
// return value (ถ้า return type ไม่ใช่ void)
}
ตัวอย่าง:
javapublic class Student {
private String id;
private String name;
private double gpa;
// Method 1: ไม่มี parameter, ไม่มี return value
public void displayInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("GPA: " + gpa);
}
// Method 2: ไม่มี parameter, มี return value (boolean)
public boolean isHonor() {
return gpa >= 3.5;
}
// Method 3: มี parameter, มี return value
public void updateGPA(double newGPA) {
if (newGPA >= 0.0 && newGPA <= 4.0) {
gpa = newGPA;
System.out.println("GPA updated to " + newGPA);
} else {
System.out.println("Invalid GPA!");
}
}
// Method 4: มี parameter หลายตัว, มี return value
public double calculateExpectedScore(double midtermScore, double finalScore) {
double average = (midtermScore + finalScore) / 2;
return average;
}
// Method 5: ใช้ return เพื่ออกจาก method
public String getGradeLevel() {
if (gpa >= 3.5) {
return "Excellent";
} else if (gpa >= 3.0) {
return "Very Good";
} else if (gpa >= 2.5) {
return "Good";
} else {
return "Fair";
}
}
}
ตัวอย่างการเรียก Method:
javapublic class StudentDemo {
public static void main(String[] args) {
Student student = new Student("6501001", "John", 3.75);
// เรียก Method 1
student.displayInfo();
// Output:
// ID: 6501001
// Name: John
// GPA: 3.75
// เรียก Method 2
if (student.isHonor()) {
System.out.println("This student is an honor student!");
}
// เรียก Method 3
student.updateGPA(3.85);
// เรียก Method 4
double score = student.calculateExpectedScore(85, 90);
System.out.println("Expected score: " + score);
// เรียก Method 5
String grade = student.getGradeLevel();
System.out.println("Grade level: " + grade);
}
}
Main Method: จุดเริ่มต้นของโปรแกรม
Main คืออะไร?
Main method คือ จุดเริ่มต้น ของการรัน Java program
เมื่อคำสั่ง java เรียกไฟล์ .class Java จะ มองหา main method เพื่อรันโปรแกรม
โครงสร้าง Main Method
javapublic static void main(String[] args) {
// เขียนโค้ดตรงนี้
}
ชิ้นส่วนที่ต้องเข้าใจ:
| ชิ้นส่วน | ความหมาย | บอกได้ต่อไป |
|---|---|---|
public | ใครก็เรียกได้ (Java interpreter เรียก) | – |
static | เป็นของ class ไม่ใช่ object (ต่อไปเรียน) | – |
void | ไม่มี return value | – |
main | ชื่อ method (must be main) | – |
String[] args | Array of strings สำหรับรับ arguments จากนอก | – |
ตัวอย่างการใช้ Main Method
ตัวอย่าง 1: โปรแกรมธรรมดา
javapublic class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
รันโปรแกรม:
bashjavac HelloWorld.java # Compile
java HelloWorld # Run
# Output: Hello, World!
ตัวอย่าง 2: ใช้ Command-line Arguments
javapublic class Greeting {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java Greeting <name>");
return; // ออกจาก main
}
String name = args[0];
System.out.println("Hello, " + name + "!");
}
}
รันโปรแกรม:
bashjavac Greeting.java
java Greeting John
# Output: Hello, John!
java Greeting Alice
# Output: Hello, Alice!
java Greeting
# Output: Usage: java Greeting <name>
ตัวอย่าง 3: สร้าง Object ใน Main
javapublic class StudentDemo {
public static void main(String[] args) {
// สร้าง objects ของ Student
Student student1 = new Student("6501001", "John", 3.75);
Student student2 = new Student("6501002", "Jane", 3.45);
// ใช้ objects
student1.displayInfo();
System.out.println();
student2.displayInfo();
System.out.println();
// เรียก methods
if (student1.isHonor()) {
System.out.println(student1 + " is an honor student!");
}
}
}
Package: ระบบจัดสรรโค้ด
Package คืออะไร?
Package คือ โฟลเดอร์ ที่ใช้ จัดระเบียบ Classes เมื่อโปรแกรมใหญ่ขึ้น
คิดได้ว่า Package เป็นการ จัดเรียง Classes ออกเป็นกลุ่ม ตามหน้าที่
ตัวอย่างในอุตสาหกรรม:
textcom.ecommerce
├── models/
│ ├── Product.java
│ ├── Order.java
│ ├── Customer.java
│ └── Payment.java
├── services/
│ ├── OrderService.java
│ ├── PaymentService.java
│ └── CustomerService.java
├── database/
│ ├── DatabaseConnection.java
│ └── QueryExecutor.java
└── utils/
├── DateUtils.java
└── ValidationUtils.java
การสร้างและใช้ Package
Step 1: สร้าง Package ด้วย Folder Structure
textproject/
├── models/
│ └── Student.java
├── services/
│ └── StudentService.java
└── MainApp.java
Step 2: ประกาศ Package ที่ต้นไฟล์
java// models/Student.java
package models;
public class Student {
private String id;
private String name;
private double gpa;
public Student(String id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}
public void displayInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("GPA: " + gpa);
}
}
Step 3: Import Package ในไฟล์อื่น
java// services/StudentService.java
package services;
import models.Student; // Import from models package
public class StudentService {
public void processStudent(Student student) {
student.displayInfo();
}
}
Step 4: ใช้ในไฟล์ main
java// MainApp.java (ไม่ใส่ package)
import models.Student;
import services.StudentService;
public class MainApp {
public static void main(String[] args) {
Student student = new Student("6501001", "John", 3.75);
StudentService service = new StudentService();
service.processStudent(student);
}
}
ชื่อ Package: Naming Convention
Java ใช้ Reverse Domain Name สำหรับตั้งชื่อ package
ตัวอย่าง:
textถ้า company domain = www.company.co.th
Package ควรตั้งชื่อ:
com.company.ecommerce
com.company.ecommerce.models
com.company.ecommerce.services
com.company.ecommerce.database
Folder structure จะเป็น:
textsrc/
└── com/
└── company/
└── ecommerce/
├── models/
│ ├── Product.java
│ └── Order.java
├── services/
│ ├── OrderService.java
│ └── ProductService.java
└── MainApp.java
Import Statement
Import ใช้สำหรับ นำเข้า Classes จาก package อื่น
java// ตัวอย่าง import
import java.util.ArrayList; // Import class ที่ระบุ
import java.util.*; // Import ทุก class ใน package (Wildcard)
import models.Student; // Import จาก local package
import models.*; // Import ทุก class ใน models package
กฎของ Import:
- Import statement ต้องอยู่ ก่อน class declaration
- Import ไม่จำเป็นสำหรับ
java.lang.*(String, System, Object เป็นต้น) - Wildcard import (
.*) ใช้ได้แต่ส่วนใหญ่ไม่นิยม (เพราะไม่ชัดเจนว่า import อะไร)
ความสัมพันธ์ระหว่างส่วนประกอบ
โครงสร้างทั้งหมด
textjava file (.java)
├─ Package (optional)
│ └─ import statements (optional)
│
├─ Class Definition
│ ├─ Attributes
│ ├─ Constructors
│ └─ Methods
│ ├─ main() (special)
│ ├─ displayInfo()
│ ├─ calculate()
│ └─ ...
│
└─ Comments
ตัวอย่างไฟล์ Java ที่สมบูรณ์
java// File: src/com/example/models/Car.java
package com.example.models;
// Import statements
import java.time.LocalDate;
/**
* Car class represents a car object
* with properties and behaviors
*/
public class Car {
// 1. ATTRIBUTES
private String brand;
private String model;
private int year;
private double price;
private double mileage;
private boolean isRunning;
// 2. CONSTRUCTORS
// Constructor 1: Full constructor
public Car(String brand, String model, int year, double price) {
this.brand = brand;
this.model = model;
this.year = year;
this.price = price;
this.mileage = 0;
this.isRunning = false;
System.out.println("Car created: " + brand + " " + model);
}
// Constructor 2: Default constructor
public Car() {
this("Unknown", "Unknown", 0, 0);
}
// 3. METHODS
// Getter methods
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
// Business logic methods
public void startEngine() {
if (!isRunning) {
isRunning = true;
System.out.println("Engine started!");
} else {
System.out.println("Engine is already running!");
}
}
public void stopEngine() {
if (isRunning) {
isRunning = false;
System.out.println("Engine stopped!");
} else {
System.out.println("Engine is not running!");
}
}
public void drive(double distance) {
if (!isRunning) {
System.out.println("Start the engine first!");
return;
}
mileage += distance;
System.out.println("Driving " + distance + " km");
System.out.println("Total mileage: " + mileage + " km");
}
public void displayInfo() {
System.out.println("=== Car Information ===");
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Price: $" + price);
System.out.println("Mileage: " + mileage + " km");
System.out.println("Status: " + (isRunning ? "Running" : "Stopped"));
System.out.println("======================");
}
}
java// File: src/com/example/demo/CarDemo.java
package com.example.demo;
import com.example.models.Car;
public class CarDemo {
public static void main(String[] args) {
// สร้าง car objects
Car car1 = new Car("Toyota", "Corolla", 2023, 25000);
Car car2 = new Car("Honda", "Civic", 2022, 28000);
// ใช้ car1
System.out.println("\n--- Car 1 Demo ---");
car1.displayInfo();
car1.startEngine();
car1.drive(50);
car1.drive(30);
car1.stopEngine();
System.out.println();
car1.displayInfo();
// ใช้ car2
System.out.println("\n--- Car 2 Demo ---");
car2.displayInfo();
car2.startEngine();
car2.drive(100);
car2.stopEngine();
System.out.println();
car2.displayInfo();
}
}
การรันโปรแกรม:
bash# Compile
javac src/com/example/models/Car.java
javac src/com/example/demo/CarDemo.java
# Run
java -cp src com.example.demo.CarDemo
# Output:
# Car created: Toyota Corolla
# Car created: Honda Civic
#
# --- Car 1 Demo ---
# === Car Information ===
# Brand: Toyota
# Model: Corolla
# Year: 2023
# Price: $25000.0
# Mileage: 0.0 km
# Status: Stopped
# ======================
# Engine started!
# Driving 50.0 km
# Total mileage: 50.0 km
# Driving 30.0 km
# Total mileage: 80.0 km
# Engine stopped!
เปรียบเทียบ: Java Structure vs C Structure
C Structure
c#include <stdio.h>
#include <string.h>
// ข้อมูล (struct)
struct Car {
char brand[50];
char model[50];
int year;
double price;
double mileage;
int isRunning;
};
// ฟังก์ชันแยก
void displayCar(struct Car *car) {
printf("Brand: %s\n", car->brand);
printf("Model: %s\n", car->model);
printf("Mileage: %.1f km\n", car->mileage);
}
void driveCar(struct Car *car, double distance) {
car->mileage += distance;
printf("Total mileage: %.1f km\n", car->mileage);
}
// Main function
int main() {
struct Car car1;
strcpy(car1.brand, "Toyota");
strcpy(car1.model, "Corolla");
car1.year = 2023;
car1.price = 25000;
car1.mileage = 0;
displayCar(&car1);
driveCar(&car1, 50);
return 0;
}
ปัญหา:
- ข้อมูล (struct) แยกจากฟังก์ชัน
- ต้องส่ง parameter ทุกครั้ง
- ไม่มีความสัมพันธ์ชัดเจนระหว่าง data กับ function
Java Structure
javapackage com.example.models;
public class Car {
// ข้อมูล (attributes)
private String brand;
private String model;
private int year;
private double price;
private double mileage;
// Constructor
public Car(String brand, String model, int year, double price) {
this.brand = brand;
this.model = model;
this.year = year;
this.price = price;
this.mileage = 0;
}
// Methods - ฟังก์ชันรวมกับข้อมูล
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Mileage: " + mileage + " km");
}
public void drive(double distance) {
mileage += distance;
System.out.println("Total mileage: " + mileage + " km");
}
}
// Main
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Corolla", 2023, 25000);
car1.displayInfo();
car1.drive(50);
}
}
ข้อดี:
- ข้อมูล (attributes) และ ฟังก์ชัน (methods) รวมกัน
- ไม่ต้องส่ง parameter เป็นอย่างมาก
- เห็นความสัมพันธ์ชัดเจน
สรุป: Structure ของโปรแกรม Java
| ส่วนประกอบ | ความหมาย | ตัวอย่าง |
|---|---|---|
| Package | โฟลเดอร์จัดระเบียบ classes | package com.example.models; |
| Class | แบบพิมพ์เขียว (blueprint) ของ object | public class Student { } |
| Attributes | ข้อมูลของ object | private String name; |
| Constructor | สร้าง object และ initialize | public Student(String name) { } |
| Methods | พฤติกรรมของ object | public void displayInfo() { } |
| Main | จุดเริ่มต้นของโปรแกรม | public static void main(String[] args) |
ความสำคัญ:
✅ Structure ช่วยให้โปรแกรมเป็นระเบียบ
✅ ทำให้ code อ่านง่ายและ maintain ได้ง่าย
✅ ช่วยให้ทีมทำงานร่วมกันได้
✅ เตรียมพื้นฐานสำหรับ OOP ที่เจาะลึกต่อไป
