บทนำ: สองส่วนสำคัญของ Object
เมื่อมองไปที่ Object จะเห็นว่ามี สองส่วนสำคัญ ที่สร้างเป็น Object นั้น:
- Attribute – ข้อมูล/สถานะ (State) ของ object
- Method – การกระทำ/พฤติกรรม (Behavior) ของ object
ความแตกต่างพื้นฐาน:
| แนวคิด | ความหมาย | เก็บ | ทำ |
|---|---|---|---|
| Attribute | ข้อมูล | เก็บค่า | (ไม่ทำอะไร – เพียงเก็บข้อมูล) |
| Method | การทำงาน | (ไม่เก็บ) | ทำให้เกิด action |
- บทนำ: สองส่วนสำคัญของ Object
- Attribute: เก็บข้อมูล (State)
- Attribute คืออะไร?
- ตัวอย่าง: Attribute ของ Student
- Types ของ Attributes
- 1. Primitive Attributes
- 2. String Attributes
- 3. Collection Attributes (Reference Type)
- Access Modifiers ของ Attributes
- Method: ทำให้เกิด Action
- Method คืออะไร?
- ตัวอย่าง: Methods ของ Student
- ประเภท Methods
- 1. Method ที่เปลี่ยนแปลง Attributes
- 2. Method ที่ส่งคืนค่า
- 3. Method ที่เพียงแสดงข้อมูล (void)
- โครงสร้าง Method
- ความสัมพันธ์: Attributes & Methods
- Attributes เปลี่ยนแปลงผ่าน Methods
- ตัวอย่างที่ 1: Bank Account
- Class Structure
- วิธีใช้
- ตัวอย่างที่ 2: Temperature Controller
- Class Structure
- วิธีใช้
- ตัวอย่างที่ 3: Product Inventory
- Class Structure
- วิธีใช้
- ตัวอย่างที่ 4: Student Grade System
- Class Structure
- วิธีใช้
- สรุป: Attribute vs Method
- Pattern: Getter & Setter
- ทำไมต้อง Getter & Setter?
- ตัวอย่างสุดท้าย: E-Commerce Shopping Cart
- Class Structure
- วิธีใช้
Attribute: เก็บข้อมูล (State)
Attribute คืออะไร?
Attribute (หรือ Field, Property, Instance Variable) คือ ตัวแปร ที่อยู่ภายใน Class เพื่อ เก็บข้อมูล ของ object
Attribute เป็น สถานะ (State) ของ object – มันบ่งบอกว่า object นั้นเป็นอยากไง ณ เวลาใดเวลาหนึ่ง
ตัวอย่าง: Attribute ของ Student
javapublic class Student {
// Attributes - เก็บข้อมูล
private String studentID; // เก็บ ID
private String name; // เก็บ ชื่อ
private double gpa; // เก็บ GPA
private int year; // เก็บ ปีการศึกษา
private String major; // เก็บ สาขาวิชา
private boolean isActive; // เก็บ สถานะการศึกษา
// Constructor เพื่อกำหนดค่า attributes
public Student(String studentID, String name, double gpa, int year, String major) {
this.studentID = studentID;
this.name = name;
this.gpa = gpa;
this.year = year;
this.major = major;
this.isActive = true;
}
}
Attributes บ่งบอก:
- Student object มีข้อมูลประเภทไหน
- Student object เก็บอะไรเกี่ยวกับนักศึกษา
ตัวอย่างค่า Attributes:
textObject: john (Student)
├─ studentID = "6501001" ← Attribute: เก็บ ID
├─ name = "John Doe" ← Attribute: เก็บ ชื่อ
├─ gpa = 3.75 ← Attribute: เก็บ GPA
├─ year = 2 ← Attribute: เก็บ ปี
├─ major = "Computer Science" ← Attribute: เก็บ สาขา
└─ isActive = true ← Attribute: เก็บ สถานะ
Types ของ Attributes
1. Primitive Attributes
javapublic class Person {
private int age; // int
private double height; // double
private boolean isMarried; // boolean
private char gender; // char
}
2. String Attributes
javapublic class Book {
private String isbn; // เก็บข้อมูล ISBN
private String title; // เก็บชื่อหนังสือ
private String author; // เก็บชื่อผู้เขียน
private String publisher; // เก็บชื่อสำนักพิมพ์
}
3. Collection Attributes (Reference Type)
javapublic class CourseEnrollment {
private ArrayList<Student> students; // เก็บรายชื่อนักศึกษา
private String[] textbooks; // เก็บหนังสือที่ใช้
}
Access Modifiers ของ Attributes
javapublic class Product {
public String publicAttribute; // สาธารณะ - ใครก็เข้าถึงได้
private double privateAttribute; // ส่วนตัว - เฉพาะใน class นี้
protected String protectedAttribute; // protected - เฉพาะ subclass
String defaultAttribute; // default - เฉพาะในแพ็คเกจเดียวกัน
}
แนวปฏิบัติที่ดี: ใช้ private
java// ✓ ดี - ใช้ private
public class Student {
private String name; // private
private double gpa; // private
}
// ❌ ไม่ดี - ใช้ public
public class Student {
public String name; // public - ใครก็เปลี่ยนแปลงได้
public double gpa; // public - ใครก็เปลี่ยนแปลงได้
}
ทำไม private ดีกว่า?
- ป้องกันการเปลี่ยนแปลงโดยไม่จำเป็น
- บังคับให้ใช้ methods เพื่อเข้าถึง (validation)
Method: ทำให้เกิด Action
Method คืออะไร?
Method (หรือ Function, Behavior, Action) คือ ชุดของคำสั่ง ที่ทำงานอะไรสิ่งหนึ่ง ของ object
Method เปลี่ยนแปลง State (Attributes) หรือ ทำสิ่งใดสิ่งหนึ่ง
ตัวอย่าง: Methods ของ Student
javapublic class Student {
// Attributes
private String name;
private double gpa;
// Methods - ทำให้เกิด action
// Method 1: study - ทำให้ GPA เพิ่ม
public void study() {
gpa += 0.1;
System.out.println(name + " is studying");
}
// Method 2: skipClass - ทำให้ GPA ลด
public void skipClass() {
gpa -= 0.2;
System.out.println(name + " skipped class");
}
// Method 3: displayInfo - แสดงข้อมูล
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("GPA: " + gpa);
}
// Method 4: getGPA - ส่งค่า GPA กลับ
public double getGPA() {
return gpa;
}
}
ประเภท Methods
1. Method ที่เปลี่ยนแปลง Attributes
javapublic class BankAccount {
private double balance;
// Method: deposit - เปลี่ยน balance
public void deposit(double amount) {
balance += amount; // เปลี่ยน attribute: balance
}
// Method: withdraw - เปลี่ยน balance
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount; // เปลี่ยน attribute: balance
}
}
}
ตัวอย่างการใช้:
javaBankAccount account = new BankAccount();
account.balance = 50000; // Attribute
account.deposit(10000); // Method - เรียก
// account.balance เปลี่ยนเป็น 60000
2. Method ที่ส่งคืนค่า
javapublic class Circle {
private double radius;
// Method: คำนวณพื้นที่
public double getArea() {
return Math.PI * radius * radius;
}
// Method: คำนวณเส้นรอบวง
public double getCircumference() {
return 2 * Math.PI * radius;
}
}
ตัวอย่างการใช้:
javaCircle circle = new Circle(5); // radius = 5
double area = circle.getArea(); // ส่งกลับค่า
double circumference = circle.getCircumference(); // ส่งกลับค่า
3. Method ที่เพียงแสดงข้อมูล (void)
javapublic class Car {
private String brand;
private String color;
private int speed;
// Method: แสดงข้อมูล (ไม่มี return)
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Color: " + color);
System.out.println("Speed: " + speed);
}
}
ตัวอย่างการใช้:
javaCar car = new Car("Toyota", "Red", 100);
car.displayInfo(); // แค่แสดง - ไม่มี return value
โครงสร้าง Method
java[access modifier] [return type] [method name] ([parameters]) {
// body
[return value];
}
ตัวอย่าง:
java// Method 1: ไม่มี return, ไม่มี parameter
public void start() {
System.out.println("Starting...");
}
// Method 2: มี return, มี parameter
public double calculatePrice(int quantity, double unitPrice) {
return quantity * unitPrice;
}
// Method 3: มี return, ไม่มี parameter
public int getTotalStudents() {
return totalStudents;
}
// Method 4: ไม่มี return, มี parameter
public void setName(String newName) {
this.name = newName;
}
ความสัมพันธ์: Attributes & Methods
Attributes เปลี่ยนแปลงผ่าน Methods
Pattern พื้นฐาน:
textAttribute (State)
↑
│ Methods เปลี่ยนแปลง
│
Method (Behavior)
ตัวอย่าง:
javapublic class GameCharacter {
// Attribute: health (state)
private int health = 100;
// Method 1: takeDamage - ลด health
public void takeDamage(int damage) {
health -= damage; // เปลี่ยน attribute
}
// Method 2: heal - เพิ่ม health
public void heal(int amount) {
health += amount; // เปลี่ยน attribute
}
// Method 3: getHealth - ส่งค่า health
public int getHealth() {
return health; // อ่าน attribute
}
}
วิธีการใช้:
javaGameCharacter hero = new GameCharacter();
// Attribute: hero.health = 100 (เดิม)
// เรียก Method: takeDamage
hero.takeDamage(20);
// Attribute: hero.health = 80 (เปลี่ยน!)
// เรียก Method: heal
hero.heal(30);
// Attribute: hero.health = 110 (เปลี่ยน!)
// เรียก Method: getHealth
int currentHealth = hero.getHealth(); // currentHealth = 110
ตัวอย่างที่ 1: Bank Account
Class Structure
javapublic class BankAccount {
// === ATTRIBUTES (State) ===
private String accountNumber;
private String accountHolder;
private double balance;
private double interestRate;
// === METHODS (Behavior) ===
// Constructor: เตรียม attributes
public BankAccount(String accountNumber, String accountHolder, double initialBalance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = initialBalance;
this.interestRate = 0.015; // 1.5% ต่อปี
}
// Method 1: ฝากเงิน - เปลี่ยน balance
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
}
}
// Method 2: ถอนเงิน - เปลี่ยน balance
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
// Method 3: คิดดอกเบี้ย - เปลี่ยน balance
public void applyInterest() {
double interest = balance * interestRate;
balance += interest;
System.out.println("Interest applied: " + interest);
}
// Method 4: ดูยอดเงิน - ส่งค่า attribute
public double getBalance() {
return balance;
}
// Method 5: แสดงข้อมูล - อ่าน attributes
public void displayInfo() {
System.out.printf("Account: %s | Holder: %s | Balance: %.2f\n",
accountNumber, accountHolder, balance);
}
}
วิธีใช้
javapublic class BankDemo {
public static void main(String[] args) {
// สร้าง object - กำหนด attributes
BankAccount account = new BankAccount("ACC001", "John Doe", 50000);
// attribute: balance = 50000
account.displayInfo(); // Output: Account: ACC001 | Holder: John Doe | Balance: 50000.00
// เรียก Method: deposit
account.deposit(10000);
// attribute: balance = 60000
account.displayInfo(); // Output: Account: ACC001 | Holder: John Doe | Balance: 60000.00
// เรียก Method: withdraw
account.withdraw(5000);
// attribute: balance = 55000
account.displayInfo(); // Output: Account: ACC001 | Holder: John Doe | Balance: 55000.00
// เรียก Method: applyInterest
account.applyInterest();
// attribute: balance ≈ 55825 (55000 × 1.015)
account.displayInfo(); // Output: Account: ACC001 | Holder: John Doe | Balance: 55825.00
// เรียก Method: getBalance
double bal = account.getBalance(); // bal = 55825
System.out.println("Current balance: " + bal);
}
}
ตัวอย่างที่ 2: Temperature Controller
Class Structure
javapublic class TemperatureController {
// === ATTRIBUTES (State) ===
private double currentTemperature;
private double targetTemperature;
private boolean isACRunning;
private String mode; // "cool" or "heat"
// === METHODS (Behavior) ===
public TemperatureController(double initialTemp) {
this.currentTemperature = initialTemp;
this.targetTemperature = initialTemp;
this.isACRunning = false;
this.mode = "cool";
}
// Method 1: ตั้งอุณหภูมิเป้าหมาย - เปลี่ยน attribute
public void setTargetTemperature(double target) {
this.targetTemperature = target;
}
// Method 2: เปิด AC - เปลี่ยน attribute
public void turnOn() {
isACRunning = true;
System.out.println("AC is now ON");
}
// Method 3: ปิด AC - เปลี่ยน attribute
public void turnOff() {
isACRunning = false;
System.out.println("AC is now OFF");
}
// Method 4: เปลี่ยนโหมด - เปลี่ยน attribute
public void setMode(String newMode) {
if (newMode.equals("cool") || newMode.equals("heat")) {
this.mode = newMode;
}
}
// Method 5: ปรับอุณหภูมิปัจจุบัน (simulation)
public void adjustTemperature(double change) {
currentTemperature += change;
}
// Method 6: ดูสถานะ - ส่งค่า attribute
public double getCurrentTemperature() {
return currentTemperature;
}
// Method 7: ตรวจสอบว่าถึง target หรือไม่
public boolean isAtTarget() {
return Math.abs(currentTemperature - targetTemperature) < 0.5;
}
// Method 8: แสดงข้อมูล
public void displayStatus() {
System.out.printf("Current: %.1f°C | Target: %.1f°C | AC: %s | Mode: %s\n",
currentTemperature, targetTemperature,
isACRunning ? "ON" : "OFF", mode);
}
}
วิธีใช้
javapublic class TemperatureDemo {
public static void main(String[] args) {
// สร้าง object
TemperatureController thermostat = new TemperatureController(28);
System.out.println("=== Initial State ===");
thermostat.displayStatus(); // Current: 28.0°C | Target: 28.0°C | AC: OFF | Mode: cool
System.out.println("\n=== Set Target Temperature ===");
thermostat.setTargetTemperature(22); // เปลี่ยน attribute
thermostat.displayStatus(); // Current: 28.0°C | Target: 22.0°C | AC: OFF | Mode: cool
System.out.println("\n=== Turn ON AC ===");
thermostat.turnOn(); // เปลี่ยน attribute: isACRunning = true
thermostat.displayStatus(); // Current: 28.0°C | Target: 22.0°C | AC: ON | Mode: cool
System.out.println("\n=== Simulate Temperature Decrease ===");
for (int i = 0; i < 10; i++) {
thermostat.adjustTemperature(-0.6); // เปลี่ยน attribute
thermostat.displayStatus();
if (thermostat.isAtTarget()) {
System.out.println("Target temperature reached!");
thermostat.turnOff();
break;
}
}
}
}
ตัวอย่างที่ 3: Product Inventory
Class Structure
javapublic class Product {
// === ATTRIBUTES (State) ===
private String productID;
private String productName;
private double price;
private int quantity;
private String category;
private boolean inStock;
// === METHODS (Behavior) ===
public Product(String productID, String productName, double price, int quantity, String category) {
this.productID = productID;
this.productName = productName;
this.price = price;
this.quantity = quantity;
this.category = category;
this.inStock = quantity > 0;
}
// Method 1: เพิ่มสต็อก - เปลี่ยน attributes
public void addStock(int amount) {
quantity += amount;
inStock = quantity > 0;
System.out.println("Added " + amount + " units. New stock: " + quantity);
}
// Method 2: ลดสต็อก - เปลี่ยน attributes
public void reduceStock(int amount) {
if (quantity >= amount) {
quantity -= amount;
inStock = quantity > 0;
System.out.println("Sold " + amount + " units. Remaining: " + quantity);
} else {
System.out.println("Not enough stock!");
}
}
// Method 3: เปลี่ยนราคา - เปลี่ยน attribute
public void updatePrice(double newPrice) {
this.price = newPrice;
}
// Method 4: คำนวณมูลค่าสต็อก - ส่งค่า
public double getTotalValue() {
return price * quantity;
}
// Method 5: ตรวจสอบ stock - ส่งค่า
public boolean isAvailable() {
return inStock && quantity > 0;
}
// Method 6: ตรวจสอบ stock น้อย
public boolean isLowStock() {
return quantity < 10;
}
// Method 7: แสดงข้อมูล
public void displayInfo() {
System.out.printf("ID: %s | Product: %s | Price: %.2f | Qty: %d | Status: %s\n",
productID, productName, price, quantity,
inStock ? "In Stock" : "Out of Stock");
}
}
วิธีใช้
javapublic class InventoryDemo {
public static void main(String[] args) {
// สร้าง products
Product laptop = new Product("P001", "Laptop", 25000, 50, "Electronics");
Product mouse = new Product("P002", "Mouse", 500, 5, "Electronics");
System.out.println("=== Initial Stock ===");
laptop.displayInfo(); // ID: P001 | Product: Laptop | Price: 25000.00 | Qty: 50 | Status: In Stock
mouse.displayInfo(); // ID: P002 | Product: Mouse | Price: 500.00 | Qty: 5 | Status: In Stock
System.out.println("\n=== Sales ===");
laptop.reduceStock(10); // quantity: 50 → 40
mouse.reduceStock(3); // quantity: 5 → 2
System.out.println("\n=== Check Stock Status ===");
System.out.println("Laptop available: " + laptop.isAvailable()); // true
System.out.println("Mouse available: " + mouse.isAvailable()); // true
System.out.println("Mouse is low stock: " + mouse.isLowStock()); // true
System.out.println("\n=== Inventory Value ===");
System.out.printf("Laptop total value: %.2f\n", laptop.getTotalValue()); // 40 × 25000
System.out.printf("Mouse total value: %.2f\n", mouse.getTotalValue()); // 2 × 500
System.out.println("\n=== Price Update ===");
laptop.updatePrice(23000); // price: 25000 → 23000
laptop.displayInfo();
System.out.println("\n=== Restock ===");
mouse.addStock(20); // quantity: 2 → 22
mouse.displayInfo();
}
}
ตัวอย่างที่ 4: Student Grade System
Class Structure
javapublic class StudentGradeSystem {
// === ATTRIBUTES (State) ===
private String studentID;
private String name;
private double[] scores;
private double gpa;
private String status; // "Pass" or "Fail"
// === METHODS (Behavior) ===
public StudentGradeSystem(String studentID, String name) {
this.studentID = studentID;
this.name = name;
this.scores = new double[5]; // 5 วิชา
this.gpa = 0;
this.status = "Pass";
}
// Method 1: ป้อนคะแนน - เปลี่ยน attributes
public void inputScore(int subjectIndex, double score) {
if (subjectIndex >= 0 && subjectIndex < scores.length) {
scores[subjectIndex] = score;
calculateGPA(); // อัพเดท GPA
}
}
// Method 2: คำนวณ GPA - เปลี่ยน attributes
private void calculateGPA() {
double sum = 0;
for (double score : scores) {
sum += score;
}
gpa = sum / scores.length;
// เปลี่ยน status
if (gpa >= 2.0) {
status = "Pass";
} else {
status = "Fail";
}
}
// Method 3: ได้เกรด - ส่งค่า
public String getGrade() {
if (gpa >= 3.5) return "A";
else if (gpa >= 3.0) return "B";
else if (gpa >= 2.5) return "C";
else if (gpa >= 2.0) return "D";
else return "F";
}
// Method 4: ดู GPA - ส่งค่า
public double getGPA() {
return gpa;
}
// Method 5: ตรวจสอบ pass/fail - ส่งค่า
public String getStatus() {
return status;
}
// Method 6: แสดงผล
public void displayReport() {
System.out.printf("ID: %s | Name: %s | GPA: %.2f | Grade: %s | Status: %s\n",
studentID, name, gpa, getGrade(), status);
}
}
วิธีใช้
javapublic class GradeDemo {
public static void main(String[] args) {
// สร้าง student
StudentGradeSystem student = new StudentGradeSystem("6501001", "John Doe");
System.out.println("=== Input Scores ===");
student.inputScore(0, 85); // วิชา 1: 85
student.inputScore(1, 90); // วิชา 2: 90
student.inputScore(2, 78); // วิชา 3: 78
student.inputScore(3, 92); // วิชา 4: 92
student.inputScore(4, 88); // วิชา 5: 88
System.out.println("=== Grade Report ===");
student.displayReport(); // ID: 6501001 | Name: John Doe | GPA: 86.60 | Grade: A | Status: Pass
System.out.println("\n=== Query Results ===");
System.out.println("GPA: " + student.getGPA()); // 86.6
System.out.println("Grade: " + student.getGrade()); // A
System.out.println("Status: " + student.getStatus()); // Pass
}
}
สรุป: Attribute vs Method
| ลักษณะ | Attribute | Method |
|---|---|---|
| บทบาท | เก็บข้อมูล/สถานะ | ทำให้เกิด action |
| ประเภท | ตัวแปร (variable) | ฟังก์ชัน (function) |
| เก็บค่า | ✓ เก็บค่าถาวร | ✗ ไม่เก็บ |
| เปลี่ยนแปลง State | ✗ (เก็บเท่านั้น) | ✓ (เปลี่ยน attributes) |
| ตัวอย่าง | balance, name, age | deposit(), withdraw() |
| Access | private (ปกติ) | public (ปกติ) |
| ลักษณะ Getter | private double balance; | public double getBalance() { } |
| ลักษณะ Setter | N/A | public void setBalance(double b) { } |
Pattern: Getter & Setter
ทำไมต้อง Getter & Setter?
ปัญหา: Attributes เป็น public
java// ❌ ไม่ดี
public class BankAccount {
public double balance; // public - ใครก็เปลี่ยนแปลงได้!
}
// ใช้งาน
BankAccount account = new BankAccount();
account.balance = 50000;
account.balance = -10000; // !!!! ยอดเงินติดลบ (ผิด!)
วิธี: ใช้ Getter & Setter Methods
java// ✓ ดี
public class BankAccount {
private double balance; // private
// Getter
public double getBalance() {
return balance;
}
// Setter - มี validation
public void setBalance(double newBalance) {
if (newBalance >= 0) {
balance = newBalance;
} else {
System.out.println("Error: Balance cannot be negative!");
}
}
}
// ใช้งาน
BankAccount account = new BankAccount();
account.setBalance(50000); // ✓ ถูก
account.setBalance(-10000); // ✗ ผิด - จะถูกปฏิเสธ
ตัวอย่างสุดท้าย: E-Commerce Shopping Cart
Class Structure
javapublic class ShoppingCart {
// === ATTRIBUTES (State) ===
private ArrayList<String> items; // รายการสินค้า
private ArrayList<Double> prices; // ราคาของแต่ละสินค้า
private ArrayList<Integer> quantities; // จำนวนของแต่ละสินค้า
private double totalPrice; // ราคารวม
private double discountPercent; // ส่วนลด
// === METHODS (Behavior) ===
public ShoppingCart() {
this.items = new ArrayList<>();
this.prices = new ArrayList<>();
this.quantities = new ArrayList<>();
this.totalPrice = 0;
this.discountPercent = 0;
}
// Method 1: เพิ่มสินค้า - เปลี่ยน attributes
public void addItem(String itemName, double price, int quantity) {
items.add(itemName);
prices.add(price);
quantities.add(quantity);
calculateTotal(); // อัพเดท totalPrice
}
// Method 2: ลบสินค้า - เปลี่ยน attributes
public void removeItem(int index) {
if (index >= 0 && index < items.size()) {
items.remove(index);
prices.remove(index);
quantities.remove(index);
calculateTotal(); // อัพเดท totalPrice
}
}
// Method 3: คำนวณรวม - เปลี่ยน attribute
private void calculateTotal() {
totalPrice = 0;
for (int i = 0; i < items.size(); i++) {
totalPrice += prices.get(i) * quantities.get(i);
}
// ลด discount
double discount = totalPrice * (discountPercent / 100);
totalPrice -= discount;
}
// Method 4: ใช้ coupon - เปลี่ยน attributes
public void applyCoupon(double discountPercentage) {
this.discountPercent = discountPercentage;
calculateTotal();
}
// Method 5: ดูรวม - ส่งค่า
public double getTotal() {
return totalPrice;
}
// Method 6: ดูจำนวนสินค้า - ส่งค่า
public int getItemCount() {
return items.size();
}
// Method 7: แสดงรายการ
public void displayCart() {
System.out.println("=== Shopping Cart ===");
for (int i = 0; i < items.size(); i++) {
double itemTotal = prices.get(i) * quantities.get(i);
System.out.printf("%d. %s: %d x %.2f = %.2f\n",
i + 1, items.get(i), quantities.get(i),
prices.get(i), itemTotal);
}
System.out.printf("Discount: %.1f%%\n", discountPercent);
System.out.printf("Total: %.2f\n", totalPrice);
}
}
วิธีใช้
javapublic class ShoppingDemo {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
System.out.println("=== Add Items ===");
cart.addItem("Laptop", 25000, 1);
cart.addItem("Mouse", 500, 2);
cart.addItem("Keyboard", 1500, 1);
cart.displayCart();
// Output:
// === Shopping Cart ===
// 1. Laptop: 1 x 25000.00 = 25000.00
// 2. Mouse: 2 x 500.00 = 1000.00
// 3. Keyboard: 1 x 1500.00 = 1500.00
// Discount: 0.0%
// Total: 27500.00
System.out.println("\n=== Apply Discount ===");
cart.applyCoupon(10); // 10% discount
cart.displayCart();
// Output:
// === Shopping Cart ===
// 1. Laptop: 1 x 25000.00 = 25000.00
// 2. Mouse: 2 x 500.00 = 1000.00
// 3. Keyboard: 1 x 1500.00 = 1500.00
// Discount: 10.0%
// Total: 24750.00
}
}
บทความนี้เป็นส่วนหนึ่งของรายวิชา Object-Oriented Programming with Java สำหรับนักศึกษาวิศวกรรมคอมพิวเตอร์และวิศวกรรมซอฟต์แวร์
