- Learn how to define and create classes
- Understand the difference between classes and objects
- Master creating and using object instances
Classes and Objects in Java
You know OOP is about modeling real-world things as objects. Time to see how that actually works in code.
Understanding Classes vs Objects
Let's start with a clear distinction that trips up many beginners:
Class: A blueprint, a template, a design
Object: A real instance created from that blueprint
Think of it like this:
- Class = Cookie Cutter: Defines the shape and design
- Object = Cookie: The actual cookie made from that cutter
You can have one class (one cookie cutter) but create many objects (many cookies) from it.
Creating Your First Class
Let's create a simple Car class:
public class Car {
// Instance variables (attributes/properties)
String brand;
String color;
int year;
double price;
}
That's it! You've created a class. But it doesn't do much yet—it's just a blueprint.
Anatomy of a Class Declaration
public class Car {
// This is the class body
}
public: Access modifier (we'll cover this in detail later)class: Keyword that says "I'm declaring a class"Car: The name of your class (always starts with capital letter by convention){ }: Curly braces contain the class body
Instance Variables (Fields)
Instance variables are the data that each object will store:
public class Car {
String brand; // What make? (Toyota, Ford, etc.)
String color; // What color?
int year; // What year was it made?
double price; // How much does it cost?
int mileage; // How many miles?
}
Each Car object you create will have its own set of these variables with potentially different values.
Creating Objects
Now let's bring our blueprint to life by creating actual objects:
public class Main {
public static void main(String[] args) {
// Creating objects using the 'new' keyword
Car myCar = new Car();
Car yourCar = new Car();
// Two separate Car objects now exist!
}
}
The 'new' Keyword
new Car() does three things:
- Allocates memory for a new Car object
- Initializes the object
- Returns a reference to that object
Think of the reference as an address—myCar holds the address of where your Car object lives in memory.
Accessing Object Members
Use the dot (.) operator to access an object's variables and methods:
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
// Setting values
myCar.brand = "Toyota";
myCar.color = "Red";
myCar.year = 2023;
myCar.price = 25000.00;
myCar.mileage = 0;
// Getting values
System.out.println("My car is a " + myCar.color + " " + myCar.brand);
System.out.println("It costs $" + myCar.price);
}
}
Output:
My car is a Red Toyota
It costs $25000.0
Multiple Objects, Different Values
Here's where OOP shines—create multiple objects, each with its own state:
public class Main {
public static void main(String[] args) {
// First car
Car car1 = new Car();
car1.brand = "Toyota";
car1.color = "Red";
car1.price = 25000.00;
// Second car
Car car2 = new Car();
car2.brand = "Honda";
car2.color = "Blue";
car2.price = 28000.00;
// Third car
Car car3 = new Car();
car3.brand = "Ford";
car3.color = "Black";
car3.price = 32000.00;
// They're all different!
System.out.println(car1.brand + " is " + car1.color);
System.out.println(car2.brand + " is " + car2.color);
System.out.println(car3.brand + " is " + car3.color);
}
}
Output:
Toyota is Red
Honda is Blue
Ford is Black
The 'this' Keyword
this is a reference to the current object. It's especially useful when you need to distinguish between instance variables and parameters with the same name:
public class Car {
String brand;
String color;
void setBrand(String brand) {
this.brand = brand; // this.brand is the instance variable
// brand is the parameter
}
void setColor(String color) {
this.color = color;
}
void displayInfo() {
System.out.println("Brand: " + this.brand);
System.out.println("Color: " + this.color);
}
}
When to use this:
- When parameter names match instance variable names
- To pass the current object to another method
- To make your code clearer and more explicit
Adding Behavior with Methods
Objects aren't just data—they can do things! Let's add some methods:
public class Car {
String brand;
String color;
int year;
double price;
int mileage;
boolean engineRunning;
void startEngine() {
engineRunning = true;
System.out.println("Engine started. Vroom!");
}
void stopEngine() {
engineRunning = false;
System.out.println("Engine stopped.");
}
void drive(int miles) {
if (engineRunning) {
mileage += miles;
System.out.println("Drove " + miles + " miles. Total: " + mileage);
} else {
System.out.println("Start the engine first!");
}
}
void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
System.out.println("Mileage: " + mileage + " miles");
}
}
Now your Car objects can actually do things:
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.color = "Red";
myCar.year = 2023;
myCar.mileage = 0;
myCar.startEngine();
myCar.drive(50);
myCar.drive(30);
myCar.stopEngine();
myCar.displayInfo();
}
}
Output:
Engine started. Vroom!
Drove 50 miles. Total: 50
Drove 30 miles. Total: 80
Engine stopped.
Brand: Toyota
Color: Red
Year: 2023
Mileage: 80 miles
A More Complete Example
Let's create a BankAccount class to see all concepts together:
public class BankAccount {
// Instance variables
String accountNumber;
String ownerName;
double balance;
// Method to deposit money
void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
System.out.println("Deposited: $" + amount);
System.out.println("New balance: $" + this.balance);
} else {
System.out.println("Invalid deposit amount!");
}
}
// Method to withdraw money
void withdraw(double amount) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
System.out.println("Withdrew: $" + amount);
System.out.println("New balance: $" + this.balance);
} else {
System.out.println("Invalid withdrawal amount or insufficient funds!");
}
}
// Method to check balance
double getBalance() {
return this.balance;
}
// Method to display account info
void displayAccountInfo() {
System.out.println("Account Number: " + this.accountNumber);
System.out.println("Owner: " + this.ownerName);
System.out.println("Balance: $" + this.balance);
}
}
Using the BankAccount class:
public class Main {
public static void main(String[] args) {
// Create two bank accounts
BankAccount account1 = new BankAccount();
account1.accountNumber = "123456";
account1.ownerName = "Alice";
account1.balance = 1000.00;
BankAccount account2 = new BankAccount();
account2.accountNumber = "789012";
account2.ownerName = "Bob";
account2.balance = 500.00;
// Alice's transactions
System.out.println("=== Alice's Account ===");
account1.displayAccountInfo();
account1.deposit(500);
account1.withdraw(200);
System.out.println("\n=== Bob's Account ===");
account2.displayAccountInfo();
account2.deposit(300);
account2.withdraw(100);
}
}
Object References and Memory
Understanding how Java handles objects is crucial:
Car car1 = new Car();
car1.brand = "Toyota";
Car car2 = car1; // car2 now points to the same object as car1
car2.brand = "Honda";
System.out.println(car1.brand); // Outputs: Honda
Why? Because car2 = car1 doesn't create a new Car. It copies the reference (address). Both variables point to the same object in memory!
Memory:
[Car object: brand="Honda"] <--- car1 points here
<--- car2 also points here
To create a truly independent copy, you'd need to create a new object and copy values manually (or use cloning, which we'll cover later).
Common Mistakes to Avoid
1. Forgetting to Create Objects
Car myCar; // Just declared, not created!
myCar.brand = "Toyota"; // ERROR! NullPointerException
Fix:
Car myCar = new Car(); // Now it's created
myCar.brand = "Toyota"; // Works!
2. Confusing Class and Object Names
Car = new Car(); // WRONG! Car is the class name
Car myCar = new Car(); // Correct!
3. Modifying the Wrong Object
Car car1 = new Car();
Car car2 = car1; // Same object!
car2.brand = "Honda"; // Changes car1.brand too!
Best Practices
- Name classes with nouns:
Car,Student,BankAccount - Use meaningful variable names:
savingsinstead ofacc1 - Start class names with capital letters:
BankAccount, notbankAccount - Start variable names with lowercase letters:
myCar, notMyCar - Group related data in the same class: All car-related attributes in
Car
Key Takeaways
- A class is a blueprint that defines structure and behavior
- An object is an instance created from that blueprint
- Use
newkeyword to create objects - Use dot (.) operator to access object members
thiskeyword refers to the current object- Each object has its own state (its own values for instance variables)
- Multiple variables can reference the same object
What's Next?
You now know how to create classes and objects, but we've been setting values manually. That's tedious! In the next lesson, we'll learn about Constructors and Methods—how to initialize objects properly and give them useful behaviors. You'll see how to create much more powerful and convenient classes!
