Menu
Theme
Bachelor of Science in Computer Science
Course Content

Classes

Object Oriented Programming (Java)

Ujenzi wa Code: Your Guide to Java Classes!

Habari mwanafunzi! Welcome to our session on one of the most important ideas in programming: Classes. If you have ever wondered how complex applications like M-Pesa or the games on your phone are built, the answer starts here. Think of today's lesson as getting the master key to a whole new world of building powerful and organised software. Ready? Let's begin!

1. What is a Class? The Blueprint Analogy

Imagine you want to build a house. You don't just start mixing cement and laying bricks, do you? No! You first go to an architect who draws a detailed plan, a blueprint (or *ramani ya nyumba*). This blueprint is not a house, but it describes everything about the house:

  • It has properties (attributes): number of rooms, type of roof, colour of the walls.
  • It has functions (behaviours): you can open doors, switch on lights, or open windows.

In Java, a Class is the blueprint. It's a template that defines the properties and behaviours of a "thing" you want to create in your program.

Real-World Example: The plan for a Toyota Vitz is a class. It defines that a Vitz will have 4 wheels, an engine, seats, and a steering wheel (attributes). It also defines that it can accelerate, brake, and turn (behaviours). The actual car you see on Thika Road is an *object* created from that plan.


    // ASCII Diagram: The Blueprint Concept

    [ The Blueprint: Class House ]
         |
         |---- Attributes (Properties)
         |      - String wallColor;
         |      - int numberOfWindows;
         |
         |---- Methods (Behaviours)
         |      - openDoor()
         |      - switchLightsOn()
         |
         V
    (This is NOT a real house, just the plan for one)

2. What is an Object? Building the Real Thing!

If a class is the blueprint, an Object is the actual thing you build from that blueprint. From one house plan, you can build many identical houses in different estates—one in South B, one in Langa'ta, and another in Ruaka. Each house is a separate, real-world object based on the same blueprint.

These individual houses are called instances of the `House` class. They all share the same structure from the blueprint, but they can have different details (e.g., one house is painted blue, another green).

Image Suggestion: A vibrant, colourful digital art illustration. On the left, an architect's blueprint for a modern Kenyan bungalow is laid out on a table. From the blueprint, three glowing lines of light extend to the right, each forming a complete, unique house. One house is in a lush green garden (Karen), another in a neat, gated community (Thika Greens), and the third with a city skyline behind it (Kileleshwa). The text "One Blueprint, Many Houses" floats above the scene.

3. The Anatomy of a Java Class: Let's Code a Matatu!

Everyone in Kenya knows what a matatu is! It's a perfect example for our first class. A matatu has properties and it has actions.

  • Attributes (Fields): What does a matatu have? A route, a Sacco name, passenger capacity.
  • Methods (Behaviours): What does a matatu do? It picks up passengers, drops them off, plays music.

Here’s how we would write the blueprint for a `Matatu` in Java:


// This is our blueprint for any matatu in our program.
public class Matatu {

    // 1. Attributes (also called fields or member variables)
    // These store the state of an object.
    String route;
    String saccoName;
    int passengerCapacity;
    int currentPassengers;

    // 2. Methods (behaviours)
    // These define the actions an object can perform.
    
    // A method to pick up a passenger
    public void pickUpPassenger() {
        if (currentPassengers < passengerCapacity) {
            currentPassengers = currentPassengers + 1; // Or currentPassengers++;
            System.out.println("Tumebeba abiria mmoja! Sasa tuko na " + currentPassengers);
        } else {
            System.out.println("Gari imejaa! Hakuna nafasi.");
        }
    }

    // A method to drop off a passenger
    public void dropOffPassenger() {
        if (currentPassengers > 0) {
            currentPassengers = currentPassengers - 1; // Or currentPassengers--;
            System.out.println("Abiria ameshuka. Tumebaki na " + currentPassengers);
        } else {
            System.out.println("Gari haina watu!");
        }
    }

    // A method to display details
    public void displayDetails() {
        System.out.println("Sacco: " + saccoName + " | Route: " + route + " | Watu ndani: " + currentPassengers);
    }
}

4. Creating & Using Objects: Bringing the Matatu to Life!

We have the blueprint (`Matatu.java`), but we don't have any actual matatus yet. The process of creating an object from a class is called instantiation. We use the `new` keyword to do this.


    // ASCII Diagram: Instantiation

    [ Class: Matatu ]
         |
         |---- using the 'new' keyword ----> [ Object 1: 'umojaMatatu' ] (An actual matatu in memory)
         |
         |---- using the 'new' keyword ----> [ Object 2: 'rongaiMatatu' ] (Another separate matatu)

To create and use our matatu objects, we need a `main` method. This is the starting point of our program. Let's create a new file, `Main.java`.


public class Main {
    public static void main(String[] args) {
        // Step 1: Create an object (instance) of the Matatu class
        // Syntax: ClassName objectName = new ClassName();
        Matatu rongaiMatatu = new Matatu();

        // Step 2: Set its attributes using the dot (.) operator
        rongaiMatatu.saccoName = "Ongata Line";
        rongaiMatatu.route = "125 - Rongai";
        rongaiMatatu.passengerCapacity = 33;
        rongaiMatatu.currentPassengers = 10;

        // Step 3: Call its methods using the dot (.) operator
        System.out.println("--- Matatu ya Rongai ---");
        rongaiMatatu.displayDetails();
        rongaiMatatu.pickUpPassenger(); // Picks up one passenger
        rongaiMatatu.displayDetails();

        System.out.println("\n--------------------------\n");

        // Let's create another, completely separate Matatu object
        Matatu umojaMatatu = new Matatu();
        umojaMatatu.saccoName = "Umoinner";
        umojaMatatu.route = "35 - Umoja";
        umojaMatatu.passengerCapacity = 51;
        umojaMatatu.currentPassengers = 45;

        System.out.println("--- Matatu ya Umoja ---");
        umojaMatatu.displayDetails();
        umojaMatatu.dropOffPassenger(); // Drops off one passenger
        umojaMatatu.displayDetails();
    }
}

5. Constructors: The Official "Fundi" (Builder)

Did you notice how we had to set the details (`saccoName`, `route`, etc.) one by one after creating the matatu? That's a bit slow. A Constructor is a special method that is called automatically when you create an object with `new`. Its main job is to set up the initial state of the object.

Think of it as hiring a *fundi* (builder) who immediately paints the house and fits the windows the moment it's built, instead of you having to do it later.

Let's add a constructor to our `Matatu` class. A constructor looks like a method but has the exact same name as the class and has no return type.


public class Matatu {

    // Attributes
    String route;
    String saccoName;
    int passengerCapacity;
    int currentPassengers;

    // This is the CONSTRUCTOR
    // It takes parameters to initialize the object's attributes.
    public Matatu(String initialRoute, String nameOfSacco, int capacity) {
        System.out.println("Building a new matatu... Done!");
        route = initialRoute;
        saccoName = nameOfSacco;
        passengerCapacity = capacity;
        currentPassengers = 0; // Every new matatu starts empty
    }

    // ... (our other methods like pickUpPassenger() remain here) ...
    public void pickUpPassenger() { /* ... same as before ... */ }
    public void dropOffPassenger() { /* ... same as before ... */ }
    public void displayDetails() { /* ... same as before ... */ }
}

Now, creating a matatu is much cleaner and faster in our `Main.java` file:


public class Main {
    public static void main(String[] args) {
        // Now we create objects by passing values directly to the constructor
        Matatu buruburuMatatu = new Matatu("58 - Buruburu", "Embassava", 45);
        Matatu kiambuMatatu = new Matatu("100 - Kiambu", "Super Metro", 33);

        System.out.println("--- Matatu ya BuruBuru ---");
        buruburuMatatu.displayDetails();
        buruburuMatatu.pickUpPassenger();
        buruburuMatatu.pickUpPassenger();
        buruburuMatatu.displayDetails();

        System.out.println("\n--- Matatu ya Kiambu ---");
        kiambuMatatu.displayDetails();
    }
}

Summary: Your Key Takeaways

Awesome work! You've just learned the foundation of Object-Oriented Programming. Let's recap:

  • A Class is a blueprint or template (e.g., `Matatu.java`).
  • An Object is a real instance created from that blueprint (e.g., `buruburuMatatu`).
  • Attributes (or Fields) are variables inside a class that store data (e.g., `route`, `saccoName`).
  • Methods are functions inside a class that define behaviour or actions (e.g., `pickUpPassenger()`).
  • A Constructor is a special method that initializes a new object when it is created.

Kazi ya Mwalimu (Teacher's Assignment)

Time to practice what you've learned! Your task is to create a Java class for an MpesaAccount.

  1. Create a class named `MpesaAccount`.
  2. Give it the following attributes: `String ownerName`, `String phoneNumber`, `double balance`.
  3. Create a constructor that takes the owner's name and phone number to initialize the account. The initial balance for every new account should be `0.0`.
  4. Create two methods:
    • `deposit(double amount)`: This should add the amount to the balance and print a confirmation message.
    • `withdraw(double amount)`: This should subtract the amount if the balance is sufficient, otherwise print an error message.
  5. In your `main` method, create an account for yourself, perform a deposit, and attempt a withdrawal. Good luck!
Pro Tip

Take your own short notes while going through the topics.

KenyaEdu
Add KenyaEdu to Home Screen
For offline access and faster experience