Classes and Objects: The Blueprint and the House
Java is an Object-Oriented Programming (OOP) language. This means instead of just writing a list of instructions, we organize our code around "things" (Objects). To create these things, we first need a Class.
1. What is a Class?
Think of a Class as a blueprint. A blueprint for a house isn't a house itself—it's just a set of instructions that describes what a house should have (walls, windows, doors).
An Object is the actual house built from that blueprint. You can build 100 different houses from the same single blueprint.
2. Anatomy of a Class
A class contains two main things:
- Fields (Attributes): What the object knows (data).
- Methods (Behaviors): What the object does (actions).
public class Car {
// 1. Fields
String model;
String color;
int speed;
// 2. Methods
void drive() {
System.out.println("The " + model + " is moving!");
}
}
3. Creating Objects (Instantiating)
To build an object from a class, we use the new keyword. This is called instantiation.
public class Main {
public static void main(String[] args) {
// Create the first object
Car myCar = new Car();
myCar.model = "Tesla";
myCar.color = "Black";
// Create a second object from the same blueprint
Car yourCar = new Car();
yourCar.model = "BMW";
myCar.drive(); // Output: The Tesla is moving!
yourCar.drive(); // Output: The BMW is moving!
}
}
4. Why use Classes?
- Modularity: You can keep related data and functions together in one unit.
- Reusability: Once you write a
UserorProductclass, you can use it across your entire application. - Real-world Mapping: It's easier to code when your software structures look like real-world entities.
💻 Full Practical Example: The Player Profile
Copy these into two separate files (or one file if you remove the public keyword from the Player class):
File: Player.java
public class Player {
String username;
int level = 1;
int health = 100;
void levelUp() {
level++;
System.out.println(username + " reached level " + level + "!");
}
void showStatus() {
System.out.printf("Player: %s | HP: %d | LVL: %d%n", username, health, level);
}
}
File: Main.java
public class Main {
public static void main(String[] args) {
Player p1 = new Player();
p1.username = "Name";
p1.showStatus();
p1.levelUp();
p1.showStatus();
}
}
⚠️ Important: Static vs Non-Static
You might have noticed our previous methods used static.
- Static methods belong to the Class (you don't need to create an object to use them).
- Non-static methods (like
drive()orlevelUp()) belong to the Object. You must create an object withnewbefore you can call them.
💡 Challenge: The Smart Home Device
Create a class called Lamp.
- Add a boolean field
isOn. - Add a method
pressSwitch()that flips the boolean (if it was true, make it false, and vice versa). - Add a method
showState()that prints "Light is ON" or "Light is OFF". - In your
mainmethod, create two different lamps and turn one of them on!