Learn Java · 3/15

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 class is a template or blueprint that defines the properties (variables) and behaviors (methods) that all objects of a certain type will have. For example, a Car class would define that every car has a color and can startEngine().
  • Object: An object is a specific instance of a class. While the Car class 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:

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.

java
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:

actionscript
My car is a Black Honda Civic
Another car is a Red Ford Mustang

2. 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 Car object, actions could be startEngine() or accelerate().
  • Constructor: A constructor is a special type of method that is automatically called when an object is created using the new keyword. 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).

java
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.

java
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:

mercury
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 Car example 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."

java
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:

java
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 this Keyword: In Java, this is 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 write this.model = model;, you are saying, "Set the model field of this specific object equal to the model parameter 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.

java
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

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:

  1. Define a public class named DigitalWallet.
  2. Inside the class, declare two private instance variables: walletId of type String and balance of type double.
  3. Implement a public constructor that accepts two parameters: a String for the wallet ID and a double for the initial balance. Use the this keyword to distinguish between the instance variables and the parameters, and assign the parameter values to the corresponding instance variables.
  4. Create a public method named getWalletId that takes no arguments and returns the walletId.
  5. Create a public method named getBalance that takes no arguments and returns the current balance.
  6. Implement a public method named addFunds that accepts a double parameter named amount. This method should only add the amount to the balance if the amount is positive (greater than zero). Otherwise, the balance should not be changed.
  7. Implement a public method named spendFunds that accepts a double parameter named amount. This method should only subtract the amount from the balance if the amount is positive and if there are sufficient funds (i.e., the amount is less than or equal to the current balance). 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 String instance variable named walletId.
  • A private double instance variable named balance.
  • A public constructor that accepts a String and a double as parameters. It must use the this keyword to initialize the walletId and balance instance variables.
  • A public method getWalletId() that returns the value of the walletId instance variable.
  • A public method getBalance() that returns the value of the balance instance variable.
  • A public void method addFunds(double amount) that increases the balance only if the input amount is greater than 0.
  • A public void method spendFunds(double amount) that decreases the balance only if the input amount is greater than 0 and less than or equal to the current balance.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.