Classes & Objects
Overview
Welcome to the heart of Java: Object-Oriented Programming (OOP). In the real world, you are surrounded by 'Objects': your phone, your dog, your car. OOP is a way of writing code that mimics the real world.
A Class is a blueprint. An Object is the actual thing built from that blueprint. Imagine an architect's blueprint for a house. You can't live inside the blueprint (the Class). But the construction crew can use that blueprint to build 100 physical houses (the Objects). Every house has the same layout, but they can have different paint colors and families living inside.
1. The Class (The Blueprint)
A Class defines two things: what an object *knows* (its data/variables) and what an object *does* (its actions/methods).
2. The Object (The Instance)
To bring a blueprint to life, we create an Object using the `new` keyword. You can create as many objects as you want from a single class.
3. State and Behavior
The data inside an object (like color, speed) is called its 'State'. The actions it can take (like honk, accelerate) are called its 'Behavior'.
Syntax
Here we define the blueprint (Car) and then build two separate physical cars from it.
// 1. The Blueprint
public class Car {
// State (Attributes)
String color;
int speed;
// Behavior (Methods)
public void honk() {
System.out.println("Beep beep! I am a " + color + " car!");
}
}
public class Main {
public static void main(String[] args) {
// 2. Building the actual Objects
Car myCar = new Car();
myCar.color = "Red";
Car yourCar = new Car();
yourCar.color = "Blue";
// Each object behaves independently
myCar.honk(); // Prints: Beep beep! I am a Red car!
yourCar.honk(); // Prints: Beep beep! I am a Blue car!
}
}Common Pitfalls
- Using an object reference before initializing it with `new`. This leads to a `NullPointerException`, meaning you tried to enter a house that hasn't been built yet!
Interview Tips
- Clearly articulate that a Class is merely a logical blueprint, while an Object is a physical instance residing in the computer's Heap memory.
Real-World Example
Everything in an app is an object. A user logging in, a database connection, or an item in a shopping cart.
public class UserAccount {
String username;
boolean isPremium;
public void login() {
System.out.println(username + " has logged in.");
}
}