Lesson 14 of 20
Classes and Objects
Model real entities with classes, objects, fields, constructors, and instance methods.
Learning objectives
- Explain the difference between a class and an object.
- Declare fields and instance methods.
- Initialize objects with a constructor.
- Create multiple independent instances with
new. - Use object state in a practical program.
1. Class versus object
A class defines a type. An object is a particular instance of that type. If Student is the class, Amina and Daniel can be two different Student objects with different field values.
Example: Student class
public class Student {
String studentId;
String name;
int mark;
Student(String studentId, String name, int mark) {
this.studentId = studentId;
this.name = name;
this.mark = mark;
}
void displayDetails() {
System.out.println(studentId + " - " + name + " - " + mark);
}
}
The constructor has the same name as the class and initializes each new object's fields. this.studentId refers to the field that belongs to the current object.
2. Creating objects
public class StudentApp {
public static void main(String[] args) {
Student student1 = new Student("S001", "Amina", 82);
Student student2 = new Student("S002", "Daniel", 74);
student1.displayDetails();
student2.displayDetails();
}
}
Each new Student(...) creates a separate object with its own state.
3. Adding behavior
boolean hasPassed() {
return mark >= 50;
}
This method belongs naturally to Student because it answers a question about a student's own mark.
Mini project: bank account class
public class BankAccount {
String accountNumber;
String holderName;
double balance;
BankAccount(String accountNumber, String holderName, double balance) {
this.accountNumber = accountNumber;
this.holderName = holderName;
this.balance = balance;
}
void deposit(double amount) {
balance += amount;
}
void displayBalance() {
System.out.printf("%s balance: RM %.2f%n", holderName, balance);
}
public static void main(String[] args) {
BankAccount account =
new BankAccount("A1001", "Amina", 500.00);
account.deposit(125.50);
account.displayBalance();
}
}
Common mistakes
| Problem | Why it happens | How to fix it |
|---|---|---|
| Calling an instance method without an object | Instance methods belong to objects. | Create an object and call object.method(). |
| Constructor has a return type | A constructor must not declare void or another return type. | Remove the return type. |
Forgetting new | The variable has no object to reference. | Instantiate with new ClassName(...). |
Summary
Classes combine state and behavior; objects are the individual instances created from those class definitions. Lesson 15 improves this design by protecting object data through encapsulation.