Module 3: Object-Oriented Programming
Classes and Objects
Model data and behaviour with your own Java classes.
Object-oriented programming (OOP) helps organize related data and behaviour. In Java, a class defines a type, and an object is an instance of that class.
Define a class#
public class Product {
String name;
double price;
void displayDetails() {
System.out.println(name + ": " + price);
}
}
The class contains two fields (name and price) and one method (displayDetails). This example keeps the fields package-private for simplicity. In production code, fields are commonly made private and exposed through intentional methods.
Create an object#
Product keyboard = new Product();
keyboard.name = "Keyboard";
keyboard.price = 799.0;
keyboard.displayDetails();
The new expression creates an object and returns a reference to it. The variable keyboard stores that reference, allowing the program to access the object's fields and methods.
Encapsulation#
Encapsulation keeps an object's internal state controlled by its own API. For example:
public class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
Callers cannot directly assign to balance; they use the public method, which checks that the deposit is positive. Real financial software needs more safeguards, but this illustrates the principle.
Class versus object#
A class is the definition; an object is one instance built from that definition. Two Product objects can have different names and prices even though they share the same class.
Practice#
Create a Student class with fields for a name and a roll number. Add a method that prints the student's details, then create two different student objects.