Lesson 15 of 36Article15 min
Class Methods & Challenge
Instance methods use object data: void deposit(double amount). Static methods belong to class: Math.max style.
Methods — behavior inside classes
Instance methods use object data: void deposit(double amount). Static methods belong to class: Math.max style.
Call instance method on object: acc.deposit(100). Call static on class: Demo.calculate().
Real-life example: deposit() is something one bank account does. calculateTax() might be a static tool for all accounts.
Instance and static methods
class BankAccount {
double balance = 0;
void deposit(double amount) {
if (amount > 0) balance += amount;
}
static double interestRate() {
return 4.5;
}
}Challenge — build a Product class
Create Product with name, price, quantity. Add methods applyDiscount(percent), restock(amount), getTotalValue().
Create two Product objects in main and call each method.
Real-life example: Challenge is like building a mini shop shelf in code — one product class, many products on shelf.
Challenge: Add a method isLowStock() that returns true when quantity < 5.