Object-Oriented Programming (OOP) Part 1: The Basics
9 min read
Welcome! Let's dive into the foundational concepts of Object-Oriented Programming (OOP) in Java.
The Problem Before OOP
Imagine writing a program to manage a city's public transportation system. In older, procedural programming styles, you might have a jumble of variables (busColor, busRoute, busCapacity) and a collection of functions (moveBus(), openBusDoors()). As the system grows to include trains, trams, and ferries, this approach becomes a chaotic mess. The data and the actions aren't connected, making the code hard to manage, debug, and expand. It’s like having a huge box of unsorted LEGOs—all the pieces are there, but building anything complex is a nightmare.
The Solution: Object-Oriented Programming
OOP provides a solution by allowing us to bundle related data and the functions that operate on that data into single, neat units called objects. This approach helps us model real-world things, making our code more organized, secure, and reusable. The core idea of OOP was first introduced with the Simula language in the 1960s.
1. Classes and Objects: Blueprints and Instances 🚗
Definition and Problem
Problem: How do we represent a real-world entity, like a car, within our program? A car isn't just one piece of data; it's a collection of states (like color, current speed, and model) and behaviors (like starting the engine, accelerating, and braking).
Solution: We use a class as a blueprint and an object as the actual thing built from that blueprint.
- Class: A
classis a template or blueprint that defines the properties (variables) and behaviors (methods) that all objects of a certain type will have. For example, aCarclass would define that every car has acolorand canstartEngine(). - Object: An
objectis a specific instance of a class. While theCarclass is the blueprint, an actual red Toyota Camry with a specific VIN is an object. You can create many objects from a single class.
Let's Build a Car Factory (Simulation)
Imagine a car factory. The master design document for a "Sedan" is the class. It specifies that every sedan will have four wheels, an engine, a color, and the ability to accelerate.
When the factory produces an actual, physical red sedan and a blue sedan, those are the objects. They are both instances of the Sedan class, but they are unique entities with their own specific states (one is red, the other is blue).
Hands-On Example
Here is how you define a simple Car class in Java:
// This is the blueprint for all cars
public class Car {
// Properties (state or fields)
String model;
String color;
int year;
int currentSpeed;
}This class defines the "template" for a car. But it doesn't represent a real car yet. To do that, we need to create objects (instances) from this class using the new keyword.
public class CarFactory {
public static void main(String[] args) {
// Create a new Car object from the Car class
Car myCar = new Car();
// Assign values to its properties
myCar.model = "Honda Civic";
myCar.color = "Black";
myCar.year = 2024;
myCar.currentSpeed = 0;
// Create another Car object
Car anotherCar = new Car();
anotherCar.model = "Ford Mustang";
anotherCar.color = "Red";
anotherCar.year = 2023;
anotherCar.currentSpeed = 0;
// You can now access the properties of each object
System.out.println("My car is a " + myCar.color + " " + myCar.model);
System.out.println("Another car is a " + anotherCar.color + " " + anotherCar.model);
}
}Output:
My car is a Black Honda Civic
Another car is a Red Ford Mustang2. Methods and Constructors: Behavior and Initialization 🛠️
Definition and Problem
Problem: Our Car objects have data (state), but they can't do anything. How do we make them perform actions? Also, when we create a new Car object, how do we ensure it's created with a valid starting state instead of just empty fields?
Solution: We use methods to define behaviors and constructors to initialize the object's state upon creation.
- Method: A method is a block of code within a class that defines a behavior or action an object can perform. For our
Carobject, actions could bestartEngine()oraccelerate(). - Constructor: A constructor is a special type of method that is automatically called when an object is created using the
newkeyword. Its primary job is to "construct" the object by initializing its state. A constructor must have the exact same name as the class and does not have a return type.
Hands-On Example
Let's upgrade our Car class with some actions and an assembly line (constructor).
public class Car {
String model;
String color;
int currentSpeed;
// This is the Constructor for the Car class
// It's called when you do "new Car(...)"
public Car(String model, String color) {
this.model = model;
this.color = color;
this.currentSpeed = 0; // All cars start stationary
System.out.println("A new " + this.color + " " + this.model + " has been built!");
}
// This is a Method to define a behavior
public void accelerate(int speedIncrease) {
this.currentSpeed = this.currentSpeed + speedIncrease;
System.out.println("The car is now going " + this.currentSpeed + " mph.");
}
// Another Method
public void brake() {
this.currentSpeed = 0;
System.out.println("The car has stopped.");
}
}Now, let's use this improved class in our factory.
public class CarFactory {
public static void main(String[] args) {
// The constructor is called right here!
Car myDreamCar = new Car("Porsche 911", "Silver");
// Now let's use the methods
myDreamCar.accelerate(50);
myDreamCar.accelerate(25);
myDreamCar.brake();
}
}Output:
A new Silver Porsche 911 has been built!
The car is now going 50 mph.
The car is now going 75 mph.
The car has stopped.🧠 Under the Hood: If you don't write a constructor yourself, the Java compiler creates a default, no-argument constructor for you behind the scenes. This is why our first
Carexample worked without an explicit constructor.
3. Access Modifiers: Controlling Who Sees What (Public, Private, Protected) 🔒
Definition and Problem
Problem: Right now, anyone using our Car object can directly change its currentSpeed to a ridiculous value (e.g., myDreamCar.currentSpeed = -500;). This is dangerous and breaks the rules of how a car should work. How can we protect an object's internal state and prevent misuse?
Solution: We use access modifiers to control the visibility and accessibility of classes, methods, and variables.
In industry, you'll almost always use public and private.
public: The member (variable or method) is accessible from anywhere, by any other class. It's like the steering wheel of a car—it's meant for public use.private: The member is accessible only within its own class. This is the heart of encapsulation. It's like the engine's internal computer; you shouldn't be able to mess with it directly. You interact with it indirectly via the public gas pedal.protected: Accessible within the same package and by subclasses. This is mainly used in inheritance, a more advanced topic.
Hands-On Example
Let's secure our Car class by making its properties private and providing public methods to access and modify them safely. These are often called "getters" and "setters."
public class Car {
// These are now private! They can only be accessed inside THIS class.
private String model;
private String color;
private int currentSpeed;
public Car(String model, String color) {
this.model = model;
this.color = color;
this.currentSpeed = 0;
}
// Public "getter" method to safely read the current speed
public int getCurrentSpeed() {
return this.currentSpeed;
}
// Public methods to control the behavior
public void accelerate(int speedIncrease) {
if (speedIncrease > 0) { // Add some safety logic
this.currentSpeed += speedIncrease;
}
}
public void brake() {
this.currentSpeed = 0;
}
}Now, in our factory, we can no longer do this:
public class CarFactory {
public static void main(String[] args) {
Car mySecureCar = new Car("Volvo XC90", "White");
// This line will now cause a COMPILE ERROR!
// mySecureCar.currentSpeed = 500; // Error: currentSpeed has private access in Car
// You MUST use the public methods to interact with the object
mySecureCar.accelerate(60);
System.out.println("Current speed: " + mySecureCar.getCurrentSpeed()); // Prints 60
}
}This practice of hiding data (private) and exposing behavior (public) is a fundamental principle of OOP called Encapsulation.
4. The 'this' Keyword and Understanding Variable Scope 📍
Definition and Problem
Problem: In our constructor, the parameter is named model and the class variable is also named model. How does Java know which one we are referring to? This is called "variable shadowing."
Solution: The this keyword.
- The
thisKeyword: In Java,thisis a reference to the current object—the instance on which a method or constructor is being called. It's used to disambiguate between instance variables and local variables (like parameters) that have the same name. When you writethis.model = model;, you are saying, "Set themodelfield of this specific object equal to themodelparameter that was just passed in."
A Note on Variable Scope
Scope determines where a variable can be accessed. The simplest rule of thumb in Java is:
- A variable's scope is defined by the nearest set of curly braces
{}it's declared in. - Instance Variables (or "fields") are declared directly inside a class but outside any method. Their scope is the entire class, and they can be accessed by any method within that class (using
this). - Local Variables are declared inside a method or a constructor. They only exist within that method. Once the method finishes executing, the local variable is gone forever. Poof! 💨
Hands-On Example
Look at our Car constructor again, this time with a focus on this.
public class Car {
private String model; // Instance variable
public Car(String model) { // 'model' here is a local parameter
// 'this.model' refers to the instance variable of the object
// '= model' refers to the parameter passed to the constructor
this.model = model;
}
public void printModel() {
String info = "Car model: "; // 'info' is a local variable, only exists here.
System.out.println(info + this.model);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Tesla Model S");
myCar.printModel();
// This would cause an error, because 'info' doesn't exist outside the printModel() method.
// System.out.println(myCar.info);
}
}Using this is an industry standard for clarity and is essential for writing clean, unambiguous code.
📚 Extra Reading
- Official Java Documentation on Classes and Objects
- Oracle's Guide to Defining Methods
- Baeldung's Deep Dive on Access Modifiers
- GeeksforGeeks on Variable Scope
Challenge
You are tasked with creating a DigitalWallet class in Java to model a simple online payment account. This class will encapsulate the core properties and behaviors of a digital wallet.
Your tasks are:
- Define a
publicclass namedDigitalWallet. - Inside the class, declare two
privateinstance variables:walletIdof typeStringandbalanceof typedouble. - Implement a
publicconstructor that accepts two parameters: aStringfor the wallet ID and adoublefor the initial balance. Use thethiskeyword to distinguish between the instance variables and the parameters, and assign the parameter values to the corresponding instance variables. - Create a
publicmethod namedgetWalletIdthat takes no arguments and returns thewalletId. - Create a
publicmethod namedgetBalancethat takes no arguments and returns the currentbalance. - Implement a
publicmethod namedaddFundsthat accepts adoubleparameter namedamount. This method should only add theamountto thebalanceif theamountis positive (greater than zero). Otherwise, the balance should not be changed. - Implement a
publicmethod namedspendFundsthat accepts adoubleparameter namedamount. This method should only subtract theamountfrom thebalanceif theamountis positive and if there are sufficient funds (i.e., theamountis less than or equal to the currentbalance). Otherwise, the balance should remain unchanged.
Expected result
Your final code should be a complete Java class definition for DigitalWallet.
The class must contain:
- A
private Stringinstance variable namedwalletId. - A
private doubleinstance variable namedbalance. - A
publicconstructor that accepts aStringand adoubleas parameters. It must use thethiskeyword to initialize thewalletIdandbalanceinstance variables. - A
publicmethodgetWalletId()that returns the value of thewalletIdinstance variable. - A
publicmethodgetBalance()that returns the value of thebalanceinstance variable. - A
publicvoidmethodaddFunds(double amount)that increases thebalanceonly if the inputamountis greater than 0. - A
publicvoidmethodspendFunds(double amount)that decreases thebalanceonly if the inputamountis greater than 0 and less than or equal to the currentbalance.