Instance vs Static

บทนำ: สองวิธีในการเก็บข้อมูล

จนถึงตอนนี้ ทั้ง Attributes และ Methods ที่เขียนนั้น เป็นของแต่ละ object (instance)

แต่บ่อยครั้ง ต้องการข้อมูล/การทำงาน ที่เป็นของ Class ทั้งหมด ไม่ใช่ของแต่ละ object

ตัวอย่าง:

  • ทำไมต้อง instance variable?
  • ทำไมต้อง static variable?
textนักศึกษา 1000 คน (1000 objects)
├─ Instance: ชื่อ, GPA, ID ต่างกัน
└─ Static: ชื่อมหาวิทยาลัย, ชื่อมหาวิทยาลัย เหมือนกันทั้งหมด!
ยาวไป อยากเลือกอ่าน

Instance: สำหรับ Object เดี่ยว

Instance Variable คืออะไร?

Instance Variable (หรือ Instance Attribute, Instance Field) คือ ข้อมูลที่เป็นของแต่ละ object แต่ละ object มี ค่าแยกกัน

javapublic class Student {
    // Instance variables - แต่ละ object มีค่าต่างกัน
    private String name;        // instance variable
    private double gpa;         // instance variable
    private int studentID;      // instance variable
}

// object 1
Student john = new Student("John", 3.75, 6501001);

// object 2
Student jane = new Student("Jane", 3.50, 6501002);

// john.name = "John"
// jane.name = "Jane"    ← ต่างกัน!

Instance Method คืออะไร?

Instance Method คือ method ที่ทำงาน على object เดี่ยว สามารถเข้าถึง instance variables ของ object นั้นได้

javapublic class BankAccount {
    private double balance;  // instance variable
    
    // Instance method - ทำงาน على instance เดี่ยว
    public void deposit(double amount) {
        this.balance += amount;  // เข้าถึง instance variable
    }
    
    public double getBalance() {
        return this.balance;  // เข้าถึง instance variable
    }
}

// ใช้งาน
BankAccount account1 = new BankAccount();
account1.deposit(1000);  // เปลี่ยน account1.balance

BankAccount account2 = new BankAccount();
account2.deposit(5000);  // เปลี่ยน account2.balance (ต่างกัน)

ตัวอย่าง: Instance ในการทำงาน

javapublic class Car {
    // Instance variables
    private String brand;
    private String color;
    private double speed;
    
    public Car(String brand, String color) {
        this.brand = brand;
        this.color = color;
        this.speed = 0;
    }
    
    // Instance method
    public void accelerate(double amount) {
        this.speed += amount;  // เปลี่ยน instance variable ของ object นี้
    }
    
    public void displayInfo() {
        System.out.printf("Brand: %s, Color: %s, Speed: %.1f\n",
                         this.brand, this.color, this.speed);
    }
}

// ใช้งาน
public class CarDemo {
    public static void main(String[] args) {
        // สร้าง 2 objects
        Car car1 = new Car("Toyota", "Red");
        Car car2 = new Car("Honda", "Blue");
        
        // เรียก instance method ของ car1
        car1.accelerate(50);
        car1.displayInfo();  // Brand: Toyota, Color: Red, Speed: 50.0
        
        // เรียก instance method ของ car2 (ต่างกัน)
        car2.accelerate(30);
        car2.displayInfo();  // Brand: Honda, Color: Blue, Speed: 30.0
        
        // car1 และ car2 มีข้อมูลต่างกัน
    }
}

Static: ของ Class ทั้งหมด

Static Variable คืออะไร?

Static Variable (หรือ Class Variable, Static Field) คือ ข้อมูลที่เป็นของ Class ทั้งหมด ไม่ใช่ของแต่ละ object

ข้อมูลนี้:/

  • แชร์กัน (shared) โดย ทุก objects
  • มี ค่าเดียว สำหรับ ทั้ง Class
  • เปลี่ยนแปลงครั้งเดียว ส่งผลกับ ทุก objects

ประกาศ:

javapublic class Student {
    // Static variable - เป็นของ Class ทั้งหมด
    public static String universityName = "Bangkok University";
    
    // Instance variable - เป็นของแต่ละ object
    private String name;
}

การเข้าถึง:

java// Static variable - เข้าถึงจาก Class
Student.universityName = "Bangkok University";

// Instance variable - เข้าถึงจาก object
Student john = new Student("John");
john.name = "John";

Static Method คืออะไร?

Static Method คือ method ที่เป็นของ Class ทั้งหมด ไม่จำเป็นต้องสร้าง object

ข้อจำกัด:

  • สามารถเข้าถึง เฉพาะ static variables เท่านั้น
  • ไม่สามารถ เข้าถึง instance variables/methods

ประกาศ:

javapublic class Calculator {
    // Static method
    public static int add(int a, int b) {
        return a + b;
    }
    
    public static int multiply(int a, int b) {
        return a * b;
    }
}

การใช้:

java// Static method - ไม่ต้องสร้าง object
int result = Calculator.add(5, 3);  // result = 8

// ไม่ต้อง: Calculator calc = new Calculator();
//         calc.add(5, 3);

ตัวอย่าง: Static in Mathematics

javapublic class Math {
    // Static constants
    public static final double PI = 3.14159;
    public static final double E = 2.71828;
    
    // Static methods
    public static double sqrt(double number) {
        return Math.sqrt(number);
    }
    
    public static int max(int a, int b) {
        return a > b ? a : b;
    }
    
    public static int abs(int number) {
        return number < 0 ? -number : number;
    }
}

// ใช้งาน
public class MathDemo {
    public static void main(String[] args) {
        // เข้าถึง static constant
        double area = Math.PI * 5 * 5;
        System.out.println("Area: " + area);
        
        // เรียก static method
        int max = Math.max(10, 20);
        System.out.println("Max: " + max);  // 20
        
        int abs = Math.abs(-15);
        System.out.println("Abs: " + abs);  // 15
        
        // ไม่ต้องสร้าง Math object
    }
}

ความแตกต่าง: Instance vs Static

ตารางเปรียบเทียบ

ลักษณะInstanceStatic
เป็นของแต่ละ objectClass ทั้งหมด
ประกาศไม่มี keywordstatic
จำนวนหลายชุด (หนึ่งต่อ object)หนึ่งชุด (ใช้ร่วมกัน)
การเข้าถึงobjectName.variableClassName.variable
ต้องสร้าง object✓ ต้อง✗ ไม่ต้อง
ใช้ที่ข้อมูลของแต่ละ entityข้อมูลร่วมกัน, หรือ utility functions

ตัวอย่างที่ 1: Student Management

ปัญหา: ทั้ง Instance และ Static

javapublic class Student {
    // === STATIC VARIABLES ===
    // ข้อมูลที่เป็นของ Class - ทั้ง Students
    public static String universityName = "Bangkok University";
    public static int totalStudents = 0;  // นับจำนวนนักศึกษาทั้งหมด
    
    // === INSTANCE VARIABLES ===
    // ข้อมูลที่เป็นของแต่ละ object
    private String studentID;
    private String name;
    private double gpa;
    
    // Constructor
    public Student(String studentID, String name, double gpa) {
        this.studentID = studentID;
        this.name = name;
        this.gpa = gpa;
        Student.totalStudents++;  // นับจำนวน
    }
    
    // === INSTANCE METHODS ===
    public void displayInfo() {
        System.out.printf("ID: %s, Name: %s, GPA: %.2f, University: %s\n",
                         studentID, name, gpa, Student.universityName);
    }
    
    public double getGPA() {
        return this.gpa;  // เข้าถึง instance variable
    }
    
    // === STATIC METHODS ===
    public static int getTotalStudents() {
        return Student.totalStudents;  // เข้าถึง static variable เท่านั้น
    }
    
    public static void printUniversityName() {
        System.out.println("University: " + Student.universityName);
    }
}

วิธีใช้

javapublic class StudentDemo {
    public static void main(String[] args) {
        System.out.println("=== Initial State ===");
        System.out.println("Total students: " + Student.getTotalStudents());  // 0
        
        System.out.println("\n=== Create Students ===");
        // สร้าง objects - ทำให้ totalStudents เพิ่ม
        Student student1 = new Student("6501001", "John", 3.75);
        Student student2 = new Student("6501002", "Jane", 3.50);
        Student student3 = new Student("6501003", "Bob", 3.90);
        
        System.out.println("Total students: " + Student.getTotalStudents());  // 3
        
        System.out.println("\n=== Display Info ===");
        // Instance method - แต่ละ object มีข้อมูลต่างกัน
        student1.displayInfo();
        // ID: 6501001, Name: John, GPA: 3.75, University: Bangkok University
        
        student2.displayInfo();
        // ID: 6501002, Name: Jane, GPA: 3.50, University: Bangkok University
        
        System.out.println("\n=== Static Methods ===");
        // Static method - เป็นของ Class ทั้งหมด
        Student.printUniversityName();  // University: Bangkok University
        
        System.out.println("\n=== Change Static Variable ===");
        // เปลี่ยน static variable ครั้งเดียว ส่งผลต่อทุก objects
        Student.universityName = "Chulalongkorn University";
        
        student1.displayInfo();
        // ID: 6501001, Name: John, GPA: 3.75, University: Chulalongkorn University
        
        student2.displayInfo();
        // ID: 6501002, Name: Jane, GPA: 3.50, University: Chulalongkorn University
    }
}

Output:

text=== Initial State ===
Total students: 0

=== Create Students ===
Total students: 3

=== Display Info ===
ID: 6501001, Name: John, GPA: 3.75, University: Bangkok University
ID: 6501002, Name: Jane, GPA: 3.50, University: Bangkok University

=== Static Methods ===
University: Bangkok University

=== Change Static Variable ===
ID: 6501001, Name: John, GPA: 3.75, University: Chulalongkorn University
ID: 6501002, Name: Jane, GPA: 3.50, University: Chulalongkorn University

ตัวอย่างที่ 2: Bank System

ปัญหา: Instance vs Static

javapublic class Bank {
    // === STATIC VARIABLES ===
    // ข้อมูลร่วมของธนาคาร
    public static String bankName = "Bangkok Bank";
    public static String bankCode = "BBK";
    public static int totalAccounts = 0;  // นับจำนวน accounts ทั้งหมด
    public static double totalDeposits = 0;  // ฝากเงินรวมทั้งธนาคาร
    
    // === INSTANCE VARIABLES ===
    // ข้อมูลของแต่ละบัญชี
    private String accountNumber;
    private String accountHolder;
    private double balance;
    
    // Constructor
    public Bank(String accountNumber, String accountHolder, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.balance = initialBalance;
        
        // อัพเดท static variables
        Bank.totalAccounts++;
        Bank.totalDeposits += initialBalance;
    }
    
    // === INSTANCE METHODS ===
    public void deposit(double amount) {
        this.balance += amount;
        Bank.totalDeposits += amount;  // อัพเดท static variable
    }
    
    public void withdraw(double amount) {
        if (this.balance >= amount) {
            this.balance -= amount;
            Bank.totalDeposits -= amount;  // อัพเดท static variable
        }
    }
    
    public double getBalance() {
        return this.balance;
    }
    
    public void displayAccountInfo() {
        System.out.printf("Bank: %s | Account: %s | Holder: %s | Balance: %.2f\n",
                         Bank.bankName, accountNumber, accountHolder, balance);
    }
    
    // === STATIC METHODS ===
    public static void displayBankInfo() {
        System.out.printf("Bank: %s | Code: %s | Total Accounts: %d | Total Deposits: %.2f\n",
                         Bank.bankName, Bank.bankCode, Bank.totalAccounts, Bank.totalDeposits);
    }
    
    public static double getTotalDeposits() {
        return Bank.totalDeposits;
    }
    
    public static int getTotalAccounts() {
        return Bank.totalAccounts;
    }
}

วิธีใช้

javapublic class BankDemo {
    public static void main(String[] args) {
        System.out.println("=== Initial State ===");
        Bank.displayBankInfo();  // Total Accounts: 0 | Total Deposits: 0.00
        
        System.out.println("\n=== Create Accounts ===");
        Bank account1 = new Bank("ACC001", "John", 50000);
        Bank account2 = new Bank("ACC002", "Jane", 75000);
        Bank account3 = new Bank("ACC003", "Bob", 30000);
        
        Bank.displayBankInfo();
        // Total Accounts: 3 | Total Deposits: 155000.00
        
        System.out.println("\n=== Account Activities ===");
        // Instance method - ส่งผลต่อ instance variable และ static variable
        account1.deposit(10000);
        account2.withdraw(20000);
        account3.deposit(5000);
        
        System.out.println("\n=== Individual Accounts ===");
        account1.displayAccountInfo();  // Balance: 60000.00
        account2.displayAccountInfo();  // Balance: 55000.00
        account3.displayAccountInfo();  // Balance: 35000.00
        
        System.out.println("\n=== Bank Summary (Static) ===");
        Bank.displayBankInfo();
        // Total Accounts: 3 | Total Deposits: 150000.00
        
        System.out.println("\nTotal deposits (method): " + Bank.getTotalDeposits());
    }
}

ตัวอย่างที่ 3: Counter Application

ปัญหา: Static Counter

javapublic class Counter {
    // === STATIC ===
    private static int globalCount = 0;  // นับทั้งหมด
    
    // === INSTANCE ===
    private int instanceCount = 0;  // นับของ object นี้
    
    // Instance method
    public void increment() {
        this.instanceCount++;  // เพิ่ม instance variable
        Counter.globalCount++;  // เพิ่ม static variable
    }
    
    // Instance method
    public int getInstanceCount() {
        return this.instanceCount;
    }
    
    // Static method
    public static int getGlobalCount() {
        return Counter.globalCount;
    }
}

วิธีใช้

javapublic class CounterDemo {
    public static void main(String[] args) {
        System.out.println("=== Create Counters ===");
        Counter counter1 = new Counter();
        Counter counter2 = new Counter();
        Counter counter3 = new Counter();
        
        System.out.println("Global count: " + Counter.getGlobalCount());  // 0
        
        System.out.println("\n=== Counter 1 increments 5 times ===");
        for (int i = 0; i < 5; i++) {
            counter1.increment();
        }
        System.out.println("Counter1: " + counter1.getInstanceCount());    // 5
        System.out.println("Global: " + Counter.getGlobalCount());        // 5
        
        System.out.println("\n=== Counter 2 increments 3 times ===");
        for (int i = 0; i < 3; i++) {
            counter2.increment();
        }
        System.out.println("Counter2: " + counter2.getInstanceCount());    // 3
        System.out.println("Global: " + Counter.getGlobalCount());        // 8
        
        System.out.println("\n=== Counter 3 increments 7 times ===");
        for (int i = 0; i < 7; i++) {
            counter3.increment();
        }
        System.out.println("Counter3: " + counter3.getInstanceCount());    // 7
        System.out.println("Global: " + Counter.getGlobalCount());        // 15
        
        System.out.println("\n=== Summary ===");
        System.out.println("Counter1: " + counter1.getInstanceCount());    // 5
        System.out.println("Counter2: " + counter2.getInstanceCount());    // 3
        System.out.println("Counter3: " + counter3.getInstanceCount());    // 7
        System.out.println("Total: " + Counter.getGlobalCount());         // 15
    }
}

ตัวอย่างที่ 4: Utility Class

Static Methods เท่านั้น (ไม่ต้องสร้าง object)

javapublic class StringUtils {
    // ทั้ง Class เป็น static methods - utility functions
    
    // Static method 1: นับจำนวน spaces
    public static int countSpaces(String text) {
        int count = 0;
        for (char c : text.toCharArray()) {
            if (c == ' ') count++;
        }
        return count;
    }
    
    // Static method 2: ลบ spaces ทั้งหมด
    public static String removeSpaces(String text) {
        return text.replaceAll(" ", "");
    }
    
    // Static method 3: นับความยาวโดยไม่นับ spaces
    public static int lengthWithoutSpaces(String text) {
        return text.replaceAll(" ", "").length();
    }
    
    // Static method 4: เปลี่ยนเป็นตัวพิมพ์ใหญ่แล้วนับคำ
    public static int countWords(String text) {
        if (text == null || text.trim().isEmpty()) return 0;
        return text.trim().split("\\s+").length;
    }
}

วิธีใช้

javapublic class StringUtilsDemo {
    public static void main(String[] args) {
        String text = "Hello World Java Programming";
        
        System.out.println("Original: " + text);
        System.out.println("Spaces: " + StringUtils.countSpaces(text));
        System.out.println("Without spaces: " + StringUtils.removeSpaces(text));
        System.out.println("Length without spaces: " + StringUtils.lengthWithoutSpaces(text));
        System.out.println("Word count: " + StringUtils.countWords(text));
        
        // ไม่ต้องสร้าง StringUtils object
        // StringUtils utils = new StringUtils();  // ไม่จำเป็น
    }
}

Output:

textOriginal: Hello World Java Programming
Spaces: 3
Without spaces: HelloWorldJavaProgramming
Length without spaces: 24
Word count: 4

ตัวอย่างที่ 5: Configuration Manager

Static สำหรับ Shared Configuration

javapublic class Config {
    // === STATIC CONSTANTS ===
    public static final String APP_NAME = "E-Commerce System";
    public static final String VERSION = "1.0.0";
    public static final String DATABASE_URL = "jdbc:mysql://localhost:3306/ecommerce";
    public static final int MAX_CONNECTIONS = 100;
    
    // === STATIC VARIABLES ===
    private static boolean isDebugMode = false;
    private static int currentConnections = 0;
    
    // === STATIC METHODS ===
    public static void enableDebugMode() {
        Config.isDebugMode = true;
        System.out.println("Debug mode enabled");
    }
    
    public static void disableDebugMode() {
        Config.isDebugMode = false;
        System.out.println("Debug mode disabled");
    }
    
    public static boolean isDebug() {
        return Config.isDebugMode;
    }
    
    public static void openConnection() {
        if (Config.currentConnections < Config.MAX_CONNECTIONS) {
            Config.currentConnections++;
        }
    }
    
    public static void closeConnection() {
        if (Config.currentConnections > 0) {
            Config.currentConnections--;
        }
    }
    
    public static void displayConfig() {
        System.out.println("=== Configuration ===");
        System.out.println("App: " + Config.APP_NAME);
        System.out.println("Version: " + Config.VERSION);
        System.out.println("Debug: " + Config.isDebugMode);
        System.out.println("Connections: " + Config.currentConnections + "/" + Config.MAX_CONNECTIONS);
    }
}

วิธีใช้

javapublic class ConfigDemo {
    public static void main(String[] args) {
        Config.displayConfig();
        
        System.out.println("\n=== Enable Debug ===");
        Config.enableDebugMode();
        
        System.out.println("\n=== Open Connections ===");
        for (int i = 0; i < 5; i++) {
            Config.openConnection();
        }
        Config.displayConfig();
        
        System.out.println("\n=== Close Connections ===");
        for (int i = 0; i < 2; i++) {
            Config.closeConnection();
        }
        Config.displayConfig();
    }
}

สรุป: Instance vs Static

ตารางสรุป

ด้านInstanceStatic
Declarationไม่มี keyword หรือ privatestatic
Belongs toObject (instance)Class
Shared✗ ไม่แชร์ – แต่ละ object มีของตัวเอง✓ แชร์ – ทั้ง class ใช้ชุดเดียวกัน
Accessobject.variableClassName.variable
Create Object✓ ต้อง✗ ไม่ต้อง
Instance Methods✓ เข้าถึงได้✗ ไม่ได้ (ต้องผ่าน object)
Static Methods✗ ไม่สามารถเรียก✓ เรียกได้โดยตรง
Use Caseข้อมูลเฉพาะของแต่ละ entityข้อมูลร่วมกัน, constants, utility functions

Analogy

textClass: มหาวิทยาลัย
├─ Static: ชื่อมหาวิทยาลัย, ปีก่อตั้ง (เดียวกันทั้งหมด)
├─ Static: นักศึกษาทั้งหมด 15,000 คน (นับรวม)
│
└─ Students (Objects):
   ├─ Instance: john (ID: 6501001, GPA: 3.75)
   ├─ Instance: jane (ID: 6501002, GPA: 3.50)
   └─ Instance: bob (ID: 6501003, GPA: 3.90)

เมื่อเปลี่ยนชื่อมหาวิทยาลัย → ทั้ง 3 คนเห็นชื่อใหม่
เมื่อเปลี่ยน john.GPA → เฉพาะ john เปลี่ยน, jane กับ bob ไม่เปลี่ยน

ตัวอย่างสุดท้าย: Game Player System

javapublic class GamePlayer {
    // === STATIC ===
    // ข้อมูลของ Game ทั้งหมด
    private static String gameName = "Adventure Quest";
    private static int totalPlayers = 0;
    private static int worldLevel = 1;  // ระดับสากล
    
    // === INSTANCE ===
    // ข้อมูลของแต่ละ player
    private String playerName;
    private int level;
    private int experience;
    private double gold;
    
    public GamePlayer(String playerName) {
        this.playerName = playerName;
        this.level = 1;
        this.experience = 0;
        this.gold = 0;
        GamePlayer.totalPlayers++;
    }
    
    // Instance method
    public void gainExperience(int xp) {
        this.experience += xp;
        if (this.experience >= 100) {
            this.level++;
            this.experience = 0;
        }
    }
    
    // Instance method
    public void gainGold(double amount) {
        this.gold += amount;
    }
    
    // Instance method
    public void displayPlayerInfo() {
        System.out.printf("[%s] Level: %d, Exp: %d, Gold: %.2f, World: %d\n",
                         playerName, level, experience, gold, GamePlayer.worldLevel);
    }
    
    // Static method
    public static void worldLevelUp() {
        GamePlayer.worldLevel++;
        System.out.println("World level increased to: " + GamePlayer.worldLevel);
    }
    
    // Static method
    public static void displayGameStatus() {
        System.out.printf("Game: %s | Total Players: %d | World Level: %d\n",
                         GamePlayer.gameName, GamePlayer.totalPlayers, GamePlayer.worldLevel);
    }
}

วิธีใช้

javapublic class GameDemo {
    public static void main(String[] args) {
        System.out.println("=== Game Start ===");
        GamePlayer.displayGameStatus();  // Total Players: 0
        
        System.out.println("\n=== Create Players ===");
        GamePlayer player1 = new GamePlayer("Hero1");
        GamePlayer player2 = new GamePlayer("Hero2");
        GamePlayer player3 = new GamePlayer("Hero3");
        
        GamePlayer.displayGameStatus();  // Total Players: 3
        
        System.out.println("\n=== Players Gain Experience ===");
        player1.gainExperience(80);
        player2.gainExperience(120);  // จะ level up
        player3.gainExperience(50);
        
        player1.displayPlayerInfo();
        player2.displayPlayerInfo();
        player3.displayPlayerInfo();
        
        System.out.println("\n=== Players Gain Gold ===");
        player1.gainGold(1000);
        player2.gainGold(1500);
        player3.gainGold(800);
        
        player1.displayPlayerInfo();
        player2.displayPlayerInfo();
        player3.displayPlayerInfo();
        
        System.out.println("\n=== Server Update (Static) ===");
        GamePlayer.worldLevelUp();
        
        System.out.println("\n=== Players See World Level Change ===");
        player1.displayPlayerInfo();  // World: 2
        player2.displayPlayerInfo();  // World: 2
        player3.displayPlayerInfo();  // World: 2
    }
}

Output:

text=== Game Start ===
Game: Adventure Quest | Total Players: 0 | World Level: 1

=== Create Players ===
Game: Adventure Quest | Total Players: 3 | World Level: 1

=== Players Gain Experience ===
[Hero1] Level: 1, Exp: 80, Gold: 0.00, World: 1
[Hero2] Level: 2, Exp: 20, Gold: 0.00, World: 1
[Hero3] Level: 1, Exp: 50, Gold: 0.00, World: 1

=== Players Gain Gold ===
[Hero1] Level: 1, Exp: 80, Gold: 1000.00, World: 1
[Hero2] Level: 2, Exp: 20, Gold: 1500.00, World: 1
[Hero3] Level: 1, Exp: 50, Gold: 800.00, World: 1

=== Server Update (Static) ===
World level increased to: 2

=== Players See World Level Change ===
[Hero1] Level: 1, Exp: 80, Gold: 1000.00, World: 2
[Hero2] Level: 2, Exp: 20, Gold: 1500.00, World: 2
[Hero3] Level: 1, Exp: 50, Gold: 800.00, World: 2

Best Practices: เมื่อใช้ Instance vs Static

ใช้ Instance เมื่อ:

text✓ ข้อมูลเป็นของแต่ละ entity
  - Student: name, ID, GPA (แต่ละคนต่างกัน)
  - BankAccount: balance, accountNumber (แต่ละบัญชีต่างกัน)

✓ Method ต้องเข้าถึง instance variables
  - deposit(), withdraw() (ต้องเข้า balance)

ใช้ Static เมื่อ:

text✓ ข้อมูลเป็นของ Class ทั้งหมด
  - University.name (ทั้ง students ใช้ชื่อเดียวกัน)
  - Bank.totalDeposits (รวมทั้งธนาคาร)

✓ Utility functions (ช่วยเหลือ)
  - Math.sqrt(), Math.max() (ไม่ต้องสร้าง Math object)

✓ Constants
  - Math.PI, Color.BLACK (เก็บค่าคงที่)

✓ Counters/Trackers
  - totalStudents, totalPlayers (นับรวม)

บทความนี้เป็นส่วนหนึ่งของรายวิชา Object-Oriented Programming with Java สำหรับนักศึกษาวิศวกรรมคอมพิวเตอร์และวิศวกรรมซอฟต์แวร์