Classes and Objects
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a way of structuring code around objects — bundles of data (fields) and behavior (methods) modeled after real-world things. Java is built entirely around this paradigm. A class is the blueprint; an object is an actual instance created from that blueprint.
Defining a Class
public class Car {
// Fields (attributes)
String brand;
String color;
int speed;
// Method (behavior)
void accelerate() {
speed += 10;
System.out.println(brand + " is now going " + speed + " km/h");
}
}Creating an Object
You create an object from a class using the new keyword:
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.color = "Red";
myCar.speed = 0;
myCar.accelerate(); // Toyota is now going 10 km/h
myCar.accelerate(); // Toyota is now going 20 km/h
}
}Here, myCar is an instance of the Car class. You can create as many independent objects as you like, each with its own separate data.
Constructors
A constructor is a special method that runs automatically when an object is created — typically used to set initial values for fields.
public class Car {
String brand;
String color;
int speed;
// Constructor
Car(String brand, String color) {
this.brand = brand;
this.color = color;
this.speed = 0;
}
void accelerate() {
speed += 10;
System.out.println(brand + " is now going " + speed + " km/h");
}
}Car myCar = new Car("Honda", "Blue");
myCar.accelerate(); // Honda is now going 10 km/h
Note:this.brand = brand;usesthisto refer to the current object's field, distinguishing it from the constructor's parameter of the same name.
Encapsulation with Private Fields
It's good practice to make fields private and control access through public methods called getters and setters. This protects the internal state of an object from being changed carelessly.
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}BankAccount account = new BankAccount(100.0);
account.deposit(50.0);
System.out.println(account.getBalance()); // 150.0Class vs Object — Quick Comparison
| Class | Object |
|---|---|
| The blueprint or template | An actual instance built from the blueprint |
| Defined once | Can be created many times |
Example: Car | Example: myCar, yourCar |
Multiple Objects, Independent State
Car car1 = new Car("Ford", "White");
Car car2 = new Car("BMW", "Black");
car1.accelerate(); // Ford is now going 10 km/h
car2.accelerate(); // BMW is now going 10 km/h
// Each object keeps its own separate speed value
Coming up next: We'll build on this foundation with inheritance, polymorphism, and deeper encapsulation concepts.